为什么 QXmlQuery 似乎在结果中添加了一个 `\n`?(以及如何解决?) [英] Why QXmlQuery seem to add a ` \n` to results? (and how to solve it?)
问题描述
写一点代码从XML中提取一些值,XPath的结果似乎在内容后面添加了\n
.
Writing a little code to extract some values from an XML, the result of the XPath seem to add \n
after the content.
#include <QCoreApplication>
#include <QXmlQuery>
#include <QString>
#include <QDebug>
auto main(int argn, char* argc[])->int
{
QCoreApplication app(argn, argc);
QString replyContent="<Root isOk='ok'/>";
QXmlQuery query;
query.setFocus(replyContent);
query.setQuery("string(//@isOk)");
// Attribute seem to add \n
QString queryResult;
if (query.evaluateTo(&queryResult))
{
qDebug() << queryResult; // Where this \n come from?
qDebug() << queryResult.size(); // Why 3? shouldn't be 2?
}
}
预期结果:
好的"
2
给定结果:
好的\n"
3
这显然有一些我想避免的副作用.
This obviously has some side effects which I would like to avoid.
为什么要添加这个\n
?以及如何解决?
Why is this \n
added? And how to solve it?
推荐答案
我认为这是由 QXmlFormatter
引入的,它用于将结果序列化为 <代码>QString;我怀疑 QXmlFormatter::endDocument
写了一个换行符.
I think that this is introduced by the QXmlFormatter
that is used when serialising the results to a QString
; I suspect that QXmlFormatter::endDocument
writes a newline.
一种解决方法是输出到字符串列表,然后选择第一个元素:
One workaround would be to output to a string list instead, then pick the first element:
QStringList results;
if (query.evaluateTo(&results))
{
const QString& queryResult = results.first();
qDebug() << queryResult;
qDebug() << queryResult.size();
}
如果您需要所有结果,您可以选择 join()
代替.
You might choose to join()
the results instead, if you need them all.
这篇关于为什么 QXmlQuery 似乎在结果中添加了一个 `\n`?(以及如何解决?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!