Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent XML notation in Qt

Tags:

c++

xml

qt

I am using Qt and C++ to read/write XML files. There is a weird behavior although I use only 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 it is <QString></QString>. Does anyone know why does this happen?

like image 614
p.i.g. Avatar asked Nov 13 '15 10:11

p.i.g.


1 Answers

Since you didn't provide a 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());
}

This 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"/>

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

like image 75
Toby Speight Avatar answered Nov 08 '22 13:11

Toby Speight