Xml namespace parsing using QXmlStreamReader
Hi how namespace parsing should handle when QXmlStreamReader is used ? Or should i use different approach?
m_xml.setNamespaceProcessing (true);
m_xml.readNext();
if (m_xml.isStartElement()) {
if (m_xml.name() == "item") {
qDebug() << m_xml.attributes().value("atom:link").toString();
parseItemElement();
} else if (m_xml.name() == "image") {
parseImageElement ();
} else {
qDebug() << m_xml.name() << m_xml.text() << m_xml.isEntityReference();
m_xml.readNext();
}
} else
Namespace attributes like atom:link doesnt get catched, atom:link, only link will fetch.
Re: Xml namespace parsing using QXmlStreamReader
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.
Code:
#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;
}