c++xmlqtdomqdomdocument

QDomElement fails to detect right nodeType


I currenty struggeling to parse XML documents because QDomElement seems to have a problem to detect the correct nodeType.

My xml document has th following content:

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

The code to read in the document is the following:

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

My problem is, that even it only contains text elements, I always receive QDomNode::ElementNode when calling firstLevel.nodeType(). But for parsing it is essential to know the correct nodeType. What do I have to do to get the actual type?

Regards, Frogtime


Solution

  • The nodeType == QDomNode::NodeType is only set to the innermost node. This is required by the DOM specification:

    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.

    To make this clear, look at this slightly modified code:

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