Can't read attributes of nested xml tag (QXmlStreamReader)

713 Views Asked by At

I have XML file (I had to simplify it):

<Line line1_attr1 = "value1" line1_attr2 = "value2">
    <Term line1_term1_attr1 = "term1value1" line1_term1_attr2 = "term1value2">
        term content
    </Term>
    <Term line1_term2_attr1 = "term2value1" line1_term2_attr2 = "term2value2">
        term content
    </Term>
</Line>
<Line line2_attr1 = "value1" line2_attr2 = "value2">
    <Term line2_term1_attr1 = "term1value1" line2_term1_attr2 = "term1value2">
        term content
    </Term>
    <Term line2_term2_attr1 = "term2value1" line2_term2_attr2 = "term2value2">
        term content
    </Term>
</Line>

The attributes are stored in two QMaps: mapString (attributes for Line) and MapTerm (attributes for Term). I can read the attributes of the Line tag but not for the Term tag. Neither this

if(token == QXmlStreamReader::StartElement)
{
    if (xml.name() == "Line")
    {
        QXmlStreamAttributes attrib = xml.attributes();
        for(auto e : mapString->keys())
        {
              mapString->insert(e, attrib.value(e).toString());
        }
        continue;
        if (xml.name() == "Term")
        {
            QXmlStreamAttributes attrib = xml.attributes();
            for(auto e : mapTerm->keys())
            {
                  mapTerm->insert(e, attrib.value(e).toString());
            }
            continue;
        }                  
    }

nor

if(token == QXmlStreamReader::StartElement)
{
    if (xml.name() == "Line")
    {
        QXmlStreamAttributes attrib = xml.attributes();
        for(auto e : mapString->keys())
        {
              mapString->insert(e, attrib.value(e).toString());
        }
        continue;       
    }
    if (xml.name() == "Term")
    {
        QXmlStreamAttributes attrib = xml.attributes();
        for(auto e : mapTerm->keys())
        {
              mapTerm->insert(e, attrib.value(e).toString());
        }
        continue;
    } 

is working, the code inside the if (xml.name() == "Term") is not executed.

1

There are 1 best solutions below

0
On

This loop is more concise and should work:

QXmlStreamReader xml;
...
while (!xml.atEnd()) {
  xml.readNext();
  if (xml.isStartElement()) {
    QMap<QString, QString> * map = nullptr;
    if (xml.name() == "Line") map = mapString;
    else if (xml.name() == "Term") map = mapTerm;
    else continue;
    QXmlStreamAttributes attrib = xml.attributes();
    for (auto e : map->keys())
       map->insert(e, attrib.value(e).toString());
  }
}