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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With