TinyXML2 get text from node and all subnodes

后端 未结 1 1461
情歌与酒
情歌与酒 2021-01-27 18:04

How does one go about getting the text from the nodes and subnodes in TinyXML2?

The XMLPrinter class seems to do what I need, but it does not print the text properly.

1条回答
  •  鱼传尺愫
    2021-01-27 18:20

    [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 
    
    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 ("
    The quick brown fox jumps over the lazy dog.
    "); auto div = doc .FirstChildElement(); XMLPrintText prt; div -> Accept (&prt); return 0; }

    0 讨论(0)
提交回复
热议问题