Menu

Help! Problem recursing through parsed data

Alan Kemp
2002-09-22
2002-09-22
  • Alan Kemp

    Alan Kemp - 2002-09-22

    Hi,

    I am trying to recurse through the parsed xml data using this code:

    void ParseNode(TiXmlElement * element, int depth)
    {
        while (element != NULL)
        {
            for (int i = 0; i < depth; i++) std::cout << "\t";
            std::cout << element->Value() << std::endl;

            TiXmlElement * ChildNode = element->FirstChildElement();
            while (ChildNode)
            {
                ParseNode(ChildNode, depth+1);
                ChildNode = ChildNode->NextSiblingElement();
            }

            element = element->NextSiblingElement();
        }
    }

    int main()
    {
        TiXmlDocument doc;
        doc.LoadFile("test.xml");

        ParseNode(doc.FirstChildElement(), 0);

        return 0;
    }

    When you run it on a file (make sure your test file has a node with several (at least 3) children), you will see that it loops through all the nodes, then loops through them all again starting from the second, then again starting at the third etc.

    I am really at a loss with this. Can anyone offer any advice?  How do you "normally" loop through data once its been read?

    Alan

     
    • Yves Berquin

      Yves Berquin - 2002-09-22

      Alan,

      I think the problem comes from your 2 loops inside the ParseNode function.
      When you ask element to be it's sister, you re-do what you've done already by parsing the childrens with ChildNode.

      I would get rid of the while (element != NULL) loop, and this would fix the problem. Anyway, a document has only one child element, by definition of XML, so that takes care of the highest level call.

      Hope this helps

      Yves Berquin

       
    • Alan Kemp

      Alan Kemp - 2002-09-22

      Thanks a lot!

      I knew it was going to be something silly :-)

      Alan

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.