1

In my C++ program I spit out nodes from an XML file. I have a standard schema which may not be followed by the input file. I therefore need to map a node title with the information type which is contained within it.

#include "pugi/pugixml.hpp"

#include <iostream>
#include <string>
#include <map>

int main()
{

    const std::map<std::string, std::string> tagMap {
        {"description", "content"}, {"url", "web_address"}
    };

    pugi::xml_document doca, docb;
    std::map<std::string, pugi::xml_node> mapa, mapb;

    if (!doca.load_file("a.xml") || !docb.load_file("b.xml")) { 
        std::cout << "Can't find input files";
        return 1;
    }

    for (auto& node: doca.child("data").children("entry")) {
    const char* id = node.child_value("id");
    mapa[id] = node;
    }

    for (auto& node: docb.child("data").children("entry")) {
    const char* idcs = node.child_value("id");
        if (!mapa.erase(idcs)) {
        mapb[idcs] = node;
        }
    }

    // For removed
    for (auto& ea: mapa) {
    std::cout << "Removed:" << std::endl;
    ea.second.print(std::cout);
    }

    // For added
    for (auto& eb: mapb) {
        // Loop through tag map
        for (auto& kv : tagMap) {
            // Try to find the tag name named in second map value
            // and associate it to the type of information in first map value
            std::cout << "Found" << kv.first;
            std::cout << "which has value" << node.child_value(kv.second)
        }
    }

}

The information I am particualy asking for help with is within for (auto& eb: mapb) {. Here I am trying to look at the XML recevied and see if I can match the tags to names in the map (i.e content and web_address) and if so, print the value of the node, associating it to what is it (i.e description or url).

I haven't been able to test this because of this compilation error, which I don't understand because I have refered to node above:

g++ -g -Wall -std=c++11 -I include -o main src/main.cpp include/pugi/pugixml.cpp src/main.cpp:51:38: error: use of undeclared identifier 'node' std::cout << "which has value" << node.child_value(kv.second)

My expected output is this:

  • Found description which has this value Hello!
  • Found url which has this value www.hotmail.com

From this input

<content>Hello!</content>
<web_address>www.hotmail.com</web_address> 
4

1 回答 1

2

错误消息很清楚:您没有node在输出代码的范围内定义。

当您在 中定义节点时for (auto& node: ...),它仅在for循环范围内可见。

我不完全清楚它应该是什么,但我想你应该node.child_value(kv.second)用类似的东西代替eb.second.child_value(kv.second)

于 2015-04-19T18:52:13.507 回答