Inconsistent XML Notation in Qt

I use Qt and C ++ to read / write XML files. There is a strange behavior, although I only use Qt classes.

QDomDocument document; QDomElement element = document.createElement( "QString" ); QDomText textNode = document.createTextNode( "" ); // Empty string. element.appendChild( textNode ); 

Sometimes the result in the XML file is <QString/> , and sometimes <QString></QString> . Does anyone know why this is happening?

+7
c ++ xml qt
source share
1 answer

Since you did not specify MCVE , I wrote:

 #include <QDebug> #include <QDomDocument> #include <QDomElement> #include <QDomText> int main() { QDomDocument document; for (int i = 0; i < 15; ++i) { QDomElement element = document.createElement("QString"); element.setAttribute("n", i); if (i%2) element.appendChild(document.createTextNode(QString())); document.appendChild(element); } qDebug() << qPrintable(document.toString()); } 

It consistently produces

 <QString n="0"/> <QString n="1"></QString> <QString n="2"/> <QString n="3"></QString> <QString n="4"/> <QString n="5"></QString> <QString n="6"/> <QString n="7"></QString> <QString n="8"/> <QString n="9"></QString> <QString n="10"/> <QString n="11"></QString> <QString n="12"/> <QString n="13"></QString> <QString n="14"/> 

A shorttag version is created only when the element has no content, and full open + close when there is content, even if it is a QDomText with an empty string.

+2
source share

All Articles