使用QXmlFormatter时如何解决错误FODC0002?

时间:2019-04-18 04:51:32

标签: c++ qt xquery qxmlquery

我正在尝试使用QXmlQuery从XML文件中获取一些元素。一切正常(我能够验证源XML文件等),直到进入尝试使用QXmlFormatter的部分,以便将结果写入另一个XML文件。当我谈到这一部分时,将显示以下错误:tag:trolltech.com,2007:QtXmlPatterns:QIODeviceVariable:inputDocument的错误FODC0002,位于第1行,第0列:文档过早结束。

该代码基于Qt中作为示例的“ Recipes”项目。唯一的区别是,我制作了一个更简单的“ cookbook” XML文件版本。我尝试使用QBuffer(示例中实现的方法)代替文件,但按预期得到了相同的结果。

这是源XML,称为temp2_xml.xml

<?xml version="1.0" encoding="UTF-8"?>
<cookbook>
    <recipe>
    <title>Quick and Easy Mushroom Soup</title>
    <title>Cheese on Toast</title>
    </recipe>
</cookbook>

这里是Xquery文件,名为allRecipes.xq:

(: Select all recipes. :)
declare variable $inputDocument external;

doc($inputDocument)/cookbook/recipe/<p>{string(title)}</p>

这是代码:

     QFile aqr_xq("C:/test_xml/allRecipes.xq");
     aqr_xq.open(QIODevice::ReadOnly);
     QFile file("C:/test_xml/temp_xml.xml");
     file.open(QIODevice::ReadWrite);
     QFile aqr_r;
     aqr_r.setFileName("C:/test_xml/temp2_xml.xml");
     aqr_r.open(QIODevice::ReadOnly);
     QTextStream in(&aqr_r);
     QString inputDocument = in.readAll();
     const QString str_query(QString::fromLatin1(aqr_xq.readAll()));
     QXmlQuery query;
     query.bindVariable("inputDocument",&aqr_r);
     query.setQuery(str_query);
     bool debug_xml = false;
     debug_xml = query.isValid();
     QXmlFormatter ser(query, &file);
     query.evaluateTo(&ser);

关于导致问题的原因和解决方法的任何想法?

1 个答案:

答案 0 :(得分:1)

我认为问题确实在于使用文本流来消耗打开的文件,如果我不使用它而只是使用代码

 QFile aqr_xq(queryFile);
 aqr_xq.open(QIODevice::ReadOnly);
 QFile file(outputFile);
 file.open(QIODevice::ReadWrite);
 QFile aqr_r;
 aqr_r.setFileName(inputFile);
 aqr_r.open(QIODevice::ReadOnly);
 const QString str_query(QString::fromLatin1(aqr_xq.readAll()));
 QXmlQuery query;
 query.bindVariable("inputDocument",&aqr_r);
 query.setQuery(str_query);
 bool debug_xml = false;
 debug_xml = query.isValid();
 QXmlFormatter ser(query, &file);
 query.evaluateTo(&ser);

然后错误确实出现在XQuery中,并引发为

Error XPTY0004: Required cardinality is zero or one("?"); got cardinality one or more("+").

您还没有说要创建哪个输出,但是如果我将XQuery更改为例如

declare variable $inputDocument external;

doc($inputDocument)/cookbook/recipe/title/<p>{string()}</p>

然后C ++代码运行正常。

还请注意,您可以使用

直接从文件中加载XQuery
query.setQuery(QUrl(queryFile));