PDA

View Full Version : Qt XML and Namespaces



ChrisW67
24th August 2012, 09:01
This sample code:


#include <QCoreApplication>
#include <QDebug>
#include <QtXml>

int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);

const QString uri("urn:test");

QDomDocument doc;
QDomElement root = doc.createElementNS(uri, "t:root");
doc.appendChild(root);

for (int i = 0; i < 3; ++i) {
QDomElement child = doc.createElementNS(uri, "t:child");
// QDomElement child = doc.createElement("t:child"); // Ugly hack works cosmetically
child.appendChild(doc.createTextNode(QString("Child %1").arg(i)));
root.appendChild(child);
}

qDebug() << "Generated";
qDebug() << doc.toString(2);


qDebug() << "\n\nSearch using name space";
QDomNodeList l = doc.elementsByTagNameNS(uri, "child");
for (int i = 0; i < l.size(); ++i) {
QDomElement e = l.at(i).toElement();
qDebug() << e.namespaceURI() << e.localName() << e.tagName();
}

return 0;
}


produces this output:


Generated
"<t:root xmlns:t="urn:test">
<t:child xmlns:t="urn:test">Child 0</t:child>
<t:child xmlns:t="urn:test">Child 1</t:child>
<t:child xmlns:t="urn:test">Child 2</t:child>
</t:root>
"

Search using name space
"urn:test" "child" "child"
"urn:test" "child" "child"
"urn:test" "child" "child"

with extraneous XML namespace declarations on every element. What I expected was this XML:


<t:root xmlns:t="urn:test">
<t:child>Child 0</t:child>
<t:child>Child 1</t:child>
<t:child>Child 2</t:child>
</t:root>

which is the sort of thing the MSXML library produces (i.e it handles determining when to declare the namespace and when to simply use it).

The extra stuff is not too bad with only one name space, but my real application has four intertwined.

I can get correct looking XML string output if I kludge it and use createElement("t:child") but then, despite appearances, the QDomNode is not in the namespace so the search fails to find these elements in the DOM.

Is there any way to get QtXml to generate sane markup with namespaces or should I use Xerces-c/libxml2?

d_stranz
24th August 2012, 16:56
or should I use Xerces-c/libxml2?

I use xerces-c++ exclusively. I figure going with a project whose sole reason for existence is to produce validating XML parsers is a safe bet. It also allows me to write portable code that can be used regardless of whether it is in a Qt app or not. (Sorry if this point of view offends the Qt priesthood and faithful. I'm a pragmatist and don't subscribe to religion).