如何正确使用QXmlQuery? (Qt XQuery / XPath)

时间:2022-12-14 21:00:04

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

我正在使用以下代码加载XML文件(实际上是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>waWdnZFHevdBeZTUnZ2dnUVZ8uOdnZ2d@giganews.com</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="test@test.test" 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">waWdnZFHevdBeZTUnZ2dnUVZ8uOdnZ2d@giganews.com</segment>
            <segment bytes="661967" number="1">waWdfhrgfnZFHevdBeZTUnZ2dnUVZ8uOdnZ2d@giganews.com</segment>
        </segments>
    </file>
</nzb>

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

请有人能告诉我我做错了什么吗?

2 个解决方案

#1


7  

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()

#2


0  

Maybe use the namespace wildcard in the query?

也许在查询中使用命名空间通配符?

doc($path)//*:file/*:segments/*:segment/string()

#1


7  

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()

#2


0  

Maybe use the namespace wildcard in the query?

也许在查询中使用命名空间通配符?

doc($path)//*:file/*:segments/*:segment/string()