我想分享一下最近在尝试使用RapidXML进行C++解析时遇到的奇怪而有趣的情况。
我想编写一个递归函数,以便在给定节点的子节点中搜索和返回特定节点。我的第一次尝试是:
xml_node<>* get_child(xml_node<> *inputNode, string sNodeFilter)
{
// cycles every child
for (xml_node<> *nodeChild = inputNode->first_node(); nodeChild; nodeChild = nodeChild->next_sibling())
{
if (nodeChild->name() == sNodeFilter)
{
cout << "node name " << nodeChild->name() << "\n";
cout << "nodeChild " << nodeChild << endl;
// returns the desired child
return nodeChild;
}
get_child(nodeChild, sNodeFilter);
}
}
它只对第一个子节点正确工作,但是如果您搜索一个嵌套在XML文件中更深的节点,就会找到节点(我看到cout's),但是在返回语句之后,for循环似乎运行了一次(或一些)多时间(可能是因为递归的调用堆栈),然后退出,指针丢失。
所以我试着用一个临时变量来修正它,这样:
xml_node<>* get_child(xml_node<> *inputNode, string sNodeFilter)
{
xml_node<> *outputNode;
// cycles every child
for (xml_node<> *nodeChild = inputNode->first_node(); nodeChild; nodeChild = nodeChild->next_sibling())
{
if (nodeChild->name() == sNodeFilter)
{
cout << "node name " << nodeChild->name() << "\n";
cout << "nodeChild " << nodeChild << endl;
outputNode = nodeChild;
cout << "outputNode " << outputNode << endl;
// returns the desired child
return outputNode;
}
get_child(nodeChild, sNodeFilter);
}
}
但一切都没变..。
不幸的是,RapidXML中的节点是类指针,因此在这种情况下,副作用会阻止我提取正确的结果。
有人发现了这种情况,还是以另一种方式解决了这个问题?
发布于 2011-03-28 21:27:50
当你通过递归找到一个孩子时,把它返回。如果找不到孩子,请返回0
xml_node<>* get_child(xml_node<> *inputNode, string sNodeFilter)
{
// cycles every child
for (xml_node<> *nodeChild = inputNode->first_node(); nodeChild; nodeChild = nodeChild->next_sibling())
{
if (nodeChild->name() == sNodeFilter)
{
cout << "node name " << nodeChild->name() << "\n";
cout << "nodeChild " << nodeChild << endl;
// returns the desired child
return nodeChild;
}
xml_node<> * x = get_child(nodeChild, sNodeFilter);
if (x)
return x;
}
return 0;
}
发布于 2014-11-24 13:37:12
我知道这不能直接回答这个问题,但我希望它能帮助到其他人:
当您想递归地搜索某个父节点下具有给定名称的所有节点时,此函数非常有用。它返回一个向量,其结果如下:
vector<xml_node<>*> find_nodes(xml_node<>* parent, const char* name) {
vector<xml_node<>*> ret;
if (parent != 0) {
if (strcmp(parent->name(), name) == 0) {
ret.push_back(parent);
}
for (xml_node<>* it = parent->first_node(); it != 0; it = it->next_sibling()) {
vector<xml_node<>*> tmp = find_nodes(it, name);
ret.insert(ret.end(), tmp.begin(), tmp.end());
}
}
return ret;
}
使用示例:
vector<xml_node<>*> nodes = find_nodes(some_node, "link");
它也适用于整个文档!
xml_document<> doc;
doc.parse<0>(str); // parse some string
vector<xml_node<>*> nodes = find_nodes(&doc, "link");
https://stackoverflow.com/questions/5465227
复制相似问题