TinyXML2 get text from node and all subnodes

此生再无相见时 提交于 2019-12-02 10:08:36

[Edited 14-Apr-17 to improve (I hope).]

XMLPrinter derives from XMLVisitor and prints the XML document (or element) in full, tags, attributes and all. XMLVisitor does the work of recursing up and down the XML hierarchy, calling default, do nothing, implementations of methods VisitEnter/VisitExit for nodes that can have descendants (children), i.e. documents and elements and ``Visit` for leaf nodes, i.e. text, comments etc. Override these methods in a derived class to implement the desired functionality.

The first problem is that you are modifying XMLPrinter. This derives from XMLVisitor and creates a printable representation of the XML document. But then you replace all XMLPrinter's visit... methods with your own. It would be much better, and less work, to derive from XMLVisitor directly.

Secondly, you're getting the element text from VisitEnter alone using GetText() which will not work when child nodes are embedded in it as documented here.

In this case, to get only the text of all elements override Visit for the text leaf nodes, i.e. Visit(const XMLText &).

#include "tinyxml2.h"
#include <iostream>

using namespace tinyxml2;

class XMLPrintText : public XMLVisitor
{
public:
   virtual bool Visit (const XMLText & txt) override
   {
      std::cout << txt .Value();
      return true;
   }
};

int main()
{
   XMLDocument doc;
   doc.Parse ("<div>The quick brown <b>fox</b> jumps over the <i>lazy</i> dog.</div>");
   auto div = doc .FirstChildElement();
   XMLPrintText prt;
   div -> Accept (&prt);
   return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!