Your should use name() and namespaceUri() together to determine if this is the element you want. Using the URI makes your code independent of the arbitrary choice of namespace prefix. made by the XML originator.
#include <QtCore>
#include <QXmlStreamReader>
"<?xml version='1.0' ?>"
"<a:doc xmlns:a='urn:first' xmlns:b='urn:second' >"
"<a:thingy>Test A</a:thingy>"
"<b:thingy>Test B</b:thingy>"
"<c xmlns='urn:third'><d>Text D</d><d>Text D</d></c>"
"</a:doc>"
);
int main(int argc, char **argv)
{
QXmlStreamReader xml(data);
xml.setNamespaceProcessing(true);
while (!xml.atEnd()) {
if(xml.readNextStartElement()) {
if (xml.namespaceUri() == "urn:first") {
qDebug() << "Process element" << xml.name() << "from first namespace";
}
else if (xml.namespaceUri() == "urn:second") {
qDebug() << "Process element" << xml.name() << "from second namespace";
}
else if (xml.namespaceUri() == "urn:third") {
qDebug() << "Process element" << xml.name() << "from third namespace";
}
else { // no namespace
qDebug() << "Process element from ? namespace";
}
}
}
return 0;
}
#include <QtCore>
#include <QXmlStreamReader>
static const QString data(
"<?xml version='1.0' ?>"
"<a:doc xmlns:a='urn:first' xmlns:b='urn:second' >"
"<a:thingy>Test A</a:thingy>"
"<b:thingy>Test B</b:thingy>"
"<c xmlns='urn:third'><d>Text D</d><d>Text D</d></c>"
"</a:doc>"
);
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QXmlStreamReader xml(data);
xml.setNamespaceProcessing(true);
while (!xml.atEnd()) {
if(xml.readNextStartElement()) {
if (xml.namespaceUri() == "urn:first") {
qDebug() << "Process element" << xml.name() << "from first namespace";
}
else if (xml.namespaceUri() == "urn:second") {
qDebug() << "Process element" << xml.name() << "from second namespace";
}
else if (xml.namespaceUri() == "urn:third") {
qDebug() << "Process element" << xml.name() << "from third namespace";
}
else { // no namespace
qDebug() << "Process element from ? namespace";
}
}
}
return 0;
}
To copy to clipboard, switch view to plain text mode
Bookmarks