How do I use QXmlQuery properly? (Qt XQuery/XPath)
Asked Answered
I

2

5

I'm using the following code to load in an XML file (actually an NZB):

QXmlQuery query;
query.bindVariable("path", QVariant(path));

query.setQuery("doc($path)/nzb/file/segments/segment/string()");
if(!query.isValid())
    throw QString("Invalid query.");

QStringList segments;
if(!query.evaluateTo(&segments))
    throw QString("Unable to evaluate...");

QString string;
foreach(string, segments)
    qDebug() << "String: " << string;

With the following input, it works as expected:

<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE nzb PUBLIC "-//newzBin//DTD NZB 1.0//EN" "http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd">
<nzb>
    <file>
        <groups>
            <group>alt.binaries.cd.image</group>
        </groups>
        <segments>
            <segment>[email protected]</segment>
        </segments>
    </file>
</nzb>

However, with the following input no results are returned. This is how the input should be formatted, with attributes:

<?xml version="1.0" encoding="iso-8859-1" ?>
<!DOCTYPE nzb PUBLIC "-//newzBin//DTD NZB 1.0//EN" "http://www.newzbin.com/DTD/nzb/nzb-1.0.dtd">
<nzb xmlns="http://www.newzbin.com/DTD/2003/nzb">
    <file poster="[email protected]" date="1225385180" subject="ubuntu-8.10-desktop-i386 - ubuntu-8.10-desktop-i386.par2 (1/1)">
        <groups>
            <group>alt.binaries.cd.image</group>
        </groups>
        <segments>
            <segment bytes="66196" number="1">[email protected]</segment>
            <segment bytes="661967" number="1">[email protected]</segment>
        </segments>
    </file>
</nzb>

Please can someone tell me what I'm doing wrong?

Infusible answered 21/4, 2010 at 19:22 Comment(0)
I
8

I discovered it's because I needed to supply a default namespace, that took hours to figure out...

The query is now:

declare default element namespace "http://www.newzbin.com/DTD/2003/nzb";
declare variable $path external;
doc($path)/nzb/file/segments/segment/string()
Infusible answered 21/4, 2010 at 21:59 Comment(2)
+1 for finding out yourself instead of sitting and waiting for somebody to answer. :) Namespaces are the single most common source of confusion for people unused to XML.Antons
Cheers Tom, hopefully I won't make this mistake again :).Infusible
F
1

Maybe use the namespace wildcard in the query?

doc($path)//*:file/*:segments/*:segment/string()
Finger answered 14/2, 2013 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.