将变量传递给 PUGIXML xml_tree_walker

Pass variable to PUGIXML xml_tree_walker

本文关键字:xml tree walker PUGIXML 变量      更新时间:2023-10-16

我正在使用pugixml来解析文件。我一直在使用xml_tree_walker,并且我想在步行者遍历 xml 时修改一个变量。我目前正在使用全局变量,但不想使用。有没有办法通过引用将变量传递给步行者?如果是这种情况,这是否意味着我需要修改 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);

您可以做的一件事是在助行器中保留一个成员引用,以引用您正在捕获信息的对象。像这样:

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...