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

时间:2010-04-21 19:22:15

标签: xml qt xpath xquery

我正在使用以下代码加载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;

使用以下输入,它按预期工作:

<?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>

但是,使用以下输入时,不会返回任何结果。这是输入应该如何格式化,具有属性:

<?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>

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

2 个答案:

答案 0 :(得分:7)

我发现这是因为我需要提供一个默认的命名空间,花了几个小时来弄明白......

查询现在是:

declare default element namespace "http://www.newzbin.com/DTD/2003/nzb";
declare variable $path external;
doc($path)/nzb/file/segments/segment/string()

答案 1 :(得分:0)

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

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