开发者

TinyXML Iterating over a Subtree

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?


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:

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

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:

bool MyTiXmlVisitor::Visit(const TiXmlText& text)
{
  cout << "Visiting Text: " << text.Value() << endl;

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

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:

subtree_root_node->Accept( my_tixmlvisitor_object );


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜