PDA

View Full Version : Extracting attributes value from an XML file with QXmlQuery and XPath



moijhd
5th July 2013, 16:58
Hey !

I am trying to read attributes value in a XML file.

Take this file "data.xml" :



<?xml version="1.0" encoding="ISO-8859-1" ?>
<a name="na">
</a>


I want to get as result of a query the string "na".

I think I found a proper solution which follows :



// Open a file
QString filename(
"C:\\Work\\data.xml"
);
QFile file(filename);
file.open(QIODevice::ReadOnly);

// Query
QXmlQuery query;
query.bindVariable("fileName", &file);
query.setQuery("declare variable $fileName external; doc($fileName)/a/@name");
// or
// query.setQuery("declare variable $fileName external; doc($fileName)/a/@name/data(.)");

// Result
QXmlResultItems xmlResultItems;
query.evaluateTo(&xmlResultItems);

// Try to get the first item
QXmlItem item(xmlResultItems.next());
while(!item.isNull())
{
if(item.isAtomicValue())
{
// Output for the query "/a/@name/data(.)"
qDebug() << "Atomic value : " << item.toAtomicValue().toString();
}
else if(item.isNode())
{
// Output for the query "/a/@name"
qDebug() << "Node : " << item.toNodeModelIndex().stringValue();
}
else
{
// Item must be null
}

// Next item
item = xmlResultItems.next();
}

// Close the file
file.close();


Am I right ?

Initialy, I had the result in a QString instead of a QXmlResultItems and I was unable to retrieve the attribute value with the query "/a/@name" (but it worked with "/a/@name/data(.)"). I am not sure why and I still don't know how to make it works with :



// Result
QString string;
query.evaluateTo(&string);

// Output : write nothing
qDebug() << string;


Thanks.