QXmlQuery and Xpath : cannot extract neither the node’s text nor the parameter’s value

324 views Asked by At

I'm trying to extract some data from an xml content. So i used QXmlQuery and wrote the code below (in Qt5). The problems are :

  1. If i try to extract text1 (so a node's text, see line 32), the code returns me the whole node : <value>text1</value>

=> Question 1 : how to get only text1 ?

  1. If i try to extract x1 (so a parameter's value, see line 35), the code returns me an error : Error SENR0001 in file:///C:/work/tests/build-TestXMLParser-Desktop-Debug/debug/TestXMLParser.exe, at line 1, column 1: Attribute param can't be serialized because it appears at the top level.

=> Question 2 : What i'm doing wrong ?

Here is the code :

#include <QApplication>
#include <QFile>
#include <QDebug>
#include <QXmlQuery>
#include <QXmlSerializer>
#include <QXmlFormatter>
#include <QBuffer>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString xmlContent =
            "<nodes>"
                "<node1 param='x1'>"
                    "<value>text1</value>"
                "</node1>"
                "<node2 param='x2'>"
                    "<value>text2</value>"
                "</node2>"
            "</nodes>";

    QBuffer device;
    device.setData(QByteArray(xmlContent.toUtf8().constData()));
    device.open(QIODevice::ReadOnly);

    QXmlQuery query;
    query.bindVariable("inputDocument", &device);

    // Extracting "text1"
    query.setQuery(QString("doc($inputDocument)/nodes/node1/value[text()]"));

    // Exracting "x1"
    //query.setQuery(QString("doc($inputDocument)/nodes/node1/@param"));

    // Output value
    QByteArray outArray;
    QBuffer buffer(&outArray);
    buffer.open(QIODevice::ReadWrite);

    QXmlSerializer serializer(query, &buffer);
    query.evaluateTo(&serializer);

    buffer.close();
    qWarning() << "Exracted value : " << QString::fromUtf8(outArray.constData());

    exit(0);

    return a.exec(&#41;;
}
1

There are 1 answers

0
Buggy On

I'm currently working with QXmlQuery and have the same problem. For text1:

query.setQuery("doc($inputDocument)/nodes/node1/value/string()");
query.evaluateTo(&any_QString_variable);

will give what you want.

And for the attribute x1, you have to do:

query.evaluateTo(&any_QString_variable);

After a query, you have to store the result somewhere to use it. Maybe I misunderstood your question, but these, give you your values.