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>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<a name="na">
</a>
To copy to clipboard, switch view to plain text mode
I want to get as result of a query the string "na".
I think I found a proper solution which follows :
// Open a file
"C:\\Work\\data.xml"
);
// 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();
// 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();
To copy to clipboard, switch view to plain text mode
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
query.evaluateTo(&string);
// Output : write nothing
qDebug() << string;
// Result
QString string;
query.evaluateTo(&string);
// Output : write nothing
qDebug() << string;
To copy to clipboard, switch view to plain text mode
Thanks.
Bookmarks