Important: Please read the Qt Code of Conduct -

How to know many subnodes into a parent node in xml?

  • Hey guys again.

    My next question is knowing about how many subnodes has a main node in an xml file using QXmlStreamReader and save it in a variable to use forward.


    QString xml = <?xml version='1.0' encoding='UTF-8'?> 
       <child attr="1"/>
       <child attr="2"/>

    And my code is here:

    if(r.readNextStartElement() && == "parent")
       //Print How many nodes has parent
       // should be 2

  • @Ripley
    [I have not used it, but] QXmlStreamReader works by making calls to read the XML in a forward-only direction. The only way to "knowing about how many subnodes has a main node" is to read them, readNextStartElement()/readNext(). So you'll need to read the children from here with something like

    while (r.readNextStartElement() && == "child")

    and count them.

    Like I said I haven't used, but you'll need to do something to distinguish

    <child />
    <child />

    (2 child nodes) versus

        <child />

    (1 child node). The difference being that in the first case you have met the first <child>'s end element before the next start one, while in the second case you have not. Look at the return result from readNextStartElement() to see this.

Log in to reply