xmlxpathxqueryqt5.5qxmlquery

Trying to get a string out of an XML document with QXmlQuery


Starting with a simple XML file:

<?xml version="1.0"?>
<playlist>
    <name>1 - first playlist</name>

    <song>Daft Punk\Discovery\Daft Punk-Discovery-01-One More Time.mp3</song>
</playlist>

I found:

I'm trying to extract the playlist name, so I tried:

QFile source(filePath);
source.open(QIODevice::ReadOnly | QIODevice::Text);
QXmlQuery query(QXmlQuery::XSLT20);
query.setFocus(&source);
query.setQuery("string(//name)", QUrl(filePath));

QString result = "";
query.evaluateTo(&result);

qDebug() << result;

source.close();

filePath is a QString passed in this method.

No matter what I do, I keep getting "Parse error: start tag expected" from the file being loaded, and no result. When I check what is in the file it looks correct.


Solution

  • Using QXmlQuery query(QXmlQuery::XSLT20); you are requesting XSLT and not XPath or XQuery, I suspect that you then get the described error as the library tries to parse the provided XPath or XQuery expression as an XML document (as XSLT is XML but XPath or XQuery is not XML). So simply use the default constructor or explicitly set the language as QXmlQuery::XQuery10.