无法读取嵌套 xml 标记的属性 (QXmlStreamReader)

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

本文关键字:属性 QXmlStreamReader 读取 嵌套 xml      更新时间:2023-10-16

我有一个XML文件(我必须简化它):

<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>

属性存储在两个qmap中:mapString (Line属性)和MapTerm (Term属性)。我可以读取Line标签的属性,但不能读取Term标签的属性。无论是这个

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;
        }                  
    }

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;
    } 
如果

正常工作,则if (xml.name() == "Term")内的代码不会执行。

这个循环更简洁,应该可以工作:

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());
  }
}