TinyXML 迭代子树
有人有代码可以迭代 TinyXML 中子树的节点吗? IE:给定一个父级,遍历其所有子级及其所有子级的子级?
Does anyone have code to iterate through the nodes of a subtree in TinyXML? IE: Given a parent, iterate through all its children and all of its children's children?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Begemoth的回答对我来说听起来不错。
下面是 TiXmlElement 的 Accept() 方法的简化版本,它不使用访问者,而是采用 TiXmlNode* 作为参数:
不过,Accept() 方法采用 TiXmlVisitor 作为参数,并为您完成所有迭代。而且您不必在整个文档上调用它,只需在要遍历的子树的根节点上调用它即可。这样,您可以通过覆盖正确的方法为 TiXmlNode 的子类定义特定行为。查看 TinyXml 源代码 中 TiXmlPrinter 的实现,了解其实现方式的一个很好的示例。
如果您不想这样做,这里是另一个示例:
这将作用于您调用 Accept() 的节点的子树中的所有文本元素。要对所有元素进行操作,请重写 TiXmlVisitor 的其余虚拟方法。然后,在要迭代子树的代码中,执行以下操作:
Begemoth's answer sounds pretty good to me.
Here is a simplified version of TiXmlElement's Accept() method, that doesn't use a visitor and instead takes a TiXmlNode* as the parameter:
The Accept() method takes a TiXmlVisitor as a parameter and does all the iterating for you, though. And you don't have to call it on the whole document, just the root node of the subtree you want to traverse. This way, you can define specific behavior for the subclasses of TiXmlNode, by overriding the right methods. Look at the implementation of TiXmlPrinter in TinyXml's source code for a good example of how it's done.
In case you don't want to do that, here is another example:
This will act on all text elements in the subtree of the node you call Accept() on. To act on all the elements, override the remaining virtual methods of TiXmlVisitor. Then, in the code where you want to iterate over the subtree, do the following:
您可以在库中使用访问者模式实现。创建一个继承自 TiXmlVistor 的类,重写必要的方法(如 VisitElement),然后为特定节点调用 Accept() 方法。
You can use Visitor pattern implementation in the library. Create a class inherited from TiXmlVistor, override necessary methods like VisitElement, then call Accept() method for a particular node.