TinyXML 迭代子树

标签 tinyxml subtree tinyxml++

有没有人有代码来遍历 TinyXML 中的子树的节点? IE:给定一个父级,遍历它的所有子级和所有子级的子级?

最佳答案

Begemoth 的回答对我来说听起来不错。

这是 TiXmlElement 的 Accept() 方法的简化版本,它不使用访问者,而是将 TiXmlNode* 作为参数:

void TiXmlIterator::iterate(const TiXmlNode* el)
{
  cout << "Iterating Node " << el->Value() << endl;
  // More useful code here...

  for (const TiXmlNode* node=el->FirstChild(); node; node=node->NextSibling())
  {
    iterate(node);
  }
 // And/Or here.
}

但是,Accept() 方法将 TiXmlVisitor 作为参数并为您完成所有迭代。而且您不必在整个文档上调用它,只需在要遍历的子树的根节点上调用即可。通过这种方式,您可以通过覆盖正确的方法为 TiXmlNode 的子类定义特定的行为。查看TinyXml's source code中TiXmlPrinter的实现一个很好的例子来说明它是如何完成的。

如果您不想这样做,这是另一个示例:
bool MyTiXmlVisitor::Visit(const TiXmlText& text)
{
  cout << "Visiting Text: " << text.Value() << endl;

  return true; // This will ensure it keeps iterating
}

这将作用于您调用 Accept() 的节点的子树中的所有文本元素。要对所有元素进行操作,请覆盖 TiXmlVisitor 的其余虚拟方法。然后,在要遍历子树的代码中,执行以下操作:
subtree_root_node->Accept( my_tixmlvisitor_object );

关于TinyXML 迭代子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2582655/

相关文章:

C: 如何创建默认格式的 XML 文件

c++ - 使用 tinyxml2 将文本中的子树插入到现有的 XML 文件中

c++ - 如何计算 TinyXml 中的元素?

TinyXML解析XML格式的字符串返回NULL?

git子树推送失败 "/Applications/Xcode.app/Contents/Developer/usr/libexec/git-core/git-subtree"

c++ - 使用 tinyxml 创建 xml

c++ - TinyXml++ 教程中的错误

c++ - tinyXml 如何创建xml

c++ - 如何创建单独的库以包含在 C++/Eclipse 中