将变量传递给 PUGIXML xml_tree_walker

Pass variable to PUGIXML xml_tree_walker

我正在使用 pugixml 来解析文件。我一直在使用 xml_tree_walker 并且我有一个变量我想在步行者走过 xml 时修改。我目前正在使用全局变量但不想使用。有没有办法通过引用将变量传递给 walker?如果是这种情况,是否意味着我需要修改 pugixml 源代码中的 for_each 函数原型?

下面是我目前使用助行器的方式。

struct simple_walker: pugi::xml_tree_walker
{
    virtual bool for_each(pugi::xml_node& node)
    {
        for (int i = 0; i < depth(); ++i) std::cout << "  "; // indentation

        std::cout << node_types[node.type()] << ": name='" << node.name() << "', value='" << node.value() << "'\n";

        some_global = node.name(); // I don't want this to be a global

        return true; // continue traversal
    }
};

我是这样称呼助行器的:

pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(XML_FILE);

simple_walker mySimpleWalker;
doc.traverse(mySimpleWalker);

您可以做的一件事是在您的 walker 中保留一个成员引用,指向您在其中捕获信息的对象。类似于:

struct captured_info // where my captured info goes
{
    std::string name;
    int value;
    std::time_t date;
    // ...
};

struct simple_walker: pugi::xml_tree_walker
{
    // must supply a captured_info object to satisfy
    // this constructor
    simple_walker(captured_info& info): info(info) {}

    virtual bool for_each(pugi::xml_node& node)
    {
        for (int i = 0; i < depth(); ++i) std::cout << "  "; // indentation

        std::cout << node_types[node.type()] << ": name='" << node.name() << "', value='" << node.value() << "'\n";

        info.name = node.name(); 
        info.value = std::stoi(node.value()); 
        // ... etc

        return true; // continue traversal
    }

    captured_info& info;
};


pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_file(XML_FILE);

captured_info info; // the output!!!
simple_walker mySimpleWalker(info); // configure for output
doc.traverse(mySimpleWalker);

std::cout << info.name << '\n'; // etc...