gpt4 book ai didi

c++ - 将变量传递给 PUGIXML xml_tree_walker

转载 作者:行者123 更新时间:2023-11-30 04:52:42 26 4
gpt4 key购买 nike

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

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

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

关于c++ - 将变量传递给 PUGIXML xml_tree_walker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54190470/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com