I'm trying to create a very function to read a very simple XML file and print its content on the QTCreator console.
I created the following XML file :
<SCANNERS>
<SCANNER>
<NAME>Test scanner</NAME>
<SERIAL>10102030</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 2</NAME>
<SERIAL>10102031</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 3</NAME>
<SERIAL>10102032</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 4</NAME>
<SERIAL>10102033</SERIAL>
</SCANNER>
<SCANNER>
<NAME>Test scanner 5</NAME>
<SERIAL>10102034</SERIAL>
</SCANNER>
</SCANNERS>
Then I created the following function, which is supposed to print each nodes inside each "SCANNER" tags :
void printDomDocument(QString xml)
{
QDomDocument xmlScanners;
QFile file(xml);
if (!file.open(QIODevice::ReadOnly))
{
std::cout << "QScannerEntryList : couldn't open XML file : " << xml.toStdString() << std::endl;
}
if (xmlScanners.setContent(&file))
{
QDomElement elem = xmlScanners.documentElement();
QDomNode n = elem.firstChild();
while (!n.isNull())
{
QDomElement e = n.toElement(); // try to convert the node to an element.
if (!e.isNull())
{
QDomNode n2 = e.firstChild();
std::cout << n2.nodeName().toStdString() << " " << n2.nodeValue().toStdString() << std::endl;
n2 = n2.nextSibling();
std::cout << n2.nodeName().toStdString() << " " << n2.nodeValue().toStdString() << std::endl;
}
n = n.nextSibling();
}
}
else
{
std::cout << "QScannerEntryList : couldn't grab content from XML file : " << xml.toStdString() << std::endl;
}
file.close();
}
My problem is, I can print the tagnames of each node perfectly, but for some reason I can't manage to print the values inside each of these tags. n2.nodeValue() doesn't show on the console.
Is there something I am doing wrong ?
Found out what's wrong.
Actually, the actual node value seems to be one node deeper than the child itself.
The solution is simply to "dig" one layer deeper :
QDomNode n2 = e.firstChild();
std::cout << n2.nodeName().toStdString() << " " << n2.firstChild().nodeValue().toStdString() << std::endl;
n2 = n2.nextSibling();
std::cout << n2.nodeName().toStdString() << " " << n2.firstChild().nodeValue().toStdString() << std::endl;
Returns the expected result :
NAME Test scanner
SERIAL 10102030
NAME Test scanner 2
SERIAL 10102031
NAME Test scanner 3
SERIAL 10102032
NAME Test scanner 4
SERIAL 10102033
NAME Test scanner 5
SERIAL 10102034