QDomElement::setAttributeNS() sets empty namespace URI
-
Hi guys,
I wanted to use namespace in my QDomDocument, but namespace URI is not appearing in the output.
Using Qt 4.8.6I have no idea what's wrong here, so any idea would be useful.
The following line should do the trick:
m_root.setAttributeNS("foo", "bar", 1.0);
and the result should look like this:
<fooelement foo:bar="1.0"/>
but, i got this:
<fooelement :bar="1.0"/>
Here is the full source:
#include <QCoreApplication> #include <QFile> #include <QDomDocument> #include <QTextStream> int main(int argc, char *argv[]) { QFile file("attributeNStest.xml"); QDomDocument *m_doc = new QDomDocument("foodoc"); QDomElement m_root; file.open(QIODevice::WriteOnly); m_root = m_doc->createElement("fooelement"); // version attribute m_root.setAttributeNS("foo", "bar", 1.0); m_doc->appendChild(m_root); QTextStream out(&file); out << m_doc->toString(); return 0; }
-
Hi @drB33R, welcome :)
I'm no XML expert, but I think I can see the issue...
In your desired output:
<fooelement foo:bar="1.0"/>
foo
is not a namespace URI, but rather a namespace prefix.Note, the prefix is supposed to alias to a namespace URI via an xmlns attribute, but you have not provided the URI in your desired output, so I'll use
http://example.com/mynamespace
for example.Now, where you have:
m_root.setAttributeNS("foo", "bar", 1.0);
- the first parameter (
foo
) is supposed to be the namespace URI (remember,foo
in your desired output is the namespace prefix, not the URI). - the second parameter (
bar
) is supposed to be "qualified name" - that is, both the namespace prefix and the attribute name together - iefoo:bar
in your example.
So, putting it all together, you would change:
m_root.setAttributeNS("foo", "bar", 1.0);
to
m_root.setAttributeNS("http://example.com/mynamespace", "foo:bar", 1.0);
That gives the output:
<fooelement foo:bar="1" xmlns:foo="http://example.com/mynamespace"/>
Hopefully that gets you a bit closer to whatever you're trying to achieve :)
Cheers.
- the first parameter (
-
Hi @Paul-Colby,
Awesome!
Now, I understand better what the Qt document wanted to say about this function.
(Probably, an example in the doc would be useful.)It's a different question, but is there any way to move the xmlns attribute outside from this tag?
(Example, If I would use more <fooelement> tags, it would be redundant to see this definition again.)Thanks a lot!