QDomElement 无法检测到正确的节点类型

QDomElement fails to detect right nodeType

我目前正在努力解析 XML 文档,因为 QDomElement 似乎无法检测到正确的节点类型。

我的 xml 文件有以下内容:

<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Tove</to>
  <from>
    <me>Jani</me>
  </from>
  <heading>Reminder</heading>
  <body>Don't forget me this weekend!</body>
</note>

文档中读取的代码如下:

QFile xmlFile("note.xml");

if (!xmlFile.open(QIODevice::ReadOnly)) {
     qDebug() << "error while opening file";
}

QDomDocument xmlDoc;
if (!xmlDoc.setContent(&xmlFile)) {
    qDebug() << "error while setting xml content";
}

QDomElement rootElement = xmlDoc.documentElement();
QDomElement firstLevel = rootElement.firstChildElement();

while (!firstLevel.isNull()) {
    qDebug() << firstLevel.tagName() << firstLevel.text() << firstLevel.nodeType();
    firstLevel = firstLevel.nextSiblingElement();
}

xmlFile.close();

我的问题是,即使它只包含文本元素,调用 firstLevel.nodeType() 时我总是收到 QDomNode::ElementNode。但是对于解析来说,知道正确的节点类型是必不可少的。我需要做什么才能获得实际类型?

此致, 青蛙时光

nodeType == QDomNode::NodeType只设置到最里面的节点。这是 DOM 规范所要求的:

The Text interface represents the textual content (termed character data in XML) of an Element or Attr. If there is no markup inside an element's content, the text is contained in a single object implementing the Text interface that is the only child of the element. If there is markup, it is parsed into a list of elements and Text nodes that form the list of children of the element.

为了弄清楚这一点,请看这段稍微修改过的代码:

while (!firstLevel.isNull()) {
    qDebug() << firstLevel.tagName() << firstLevel.text() << firstLevel.nodeType();
    QDomNode firstNode = firstLevel.firstChild();
    qDebug() << "And the child has nodetype:" << firstNode.nodeType();
    firstLevel = firstLevel.nextSiblingElement();
}