我在尝试将 setContent()
用于 QDomDocument 对象时遇到问题..
代码如下:
QFile f("database.xml");
if(!f.open(QFile::ReadOnly))
cout << "Error: file not correctly opened." << endl;
QDomDocument doc("database");
QString errorStr;
int errorLine;
int errorColumn;
if(!doc.setContent(&f, false, &errorStr, &errorLine, &errorColumn)){
cout << "Error: " << errorStr.toStdString() << " at line " << errorLine << " column " << errorColumn << endl;
}
f.close();
并打印:
错误:文件在第 1 行第 1 列意外结束
我该如何解决这个错误?
文件内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<myLibrary>
<movie>
<price>5</price>
<title>Star Wars 4</title>
<register>George Lukas</register>
<year>1977</year>
<durate>192</durate>
</movie>
<movie>
<price>8</price>
<title>Rambo 1</title>
<register>Joe Clarkson</register>
<year>2012</year>
<durate>167</durate>
</movie>
</myLibrary>
最佳答案
所以问题是您的 XML 文件的路径无效。
如果您尝试打开与您的可执行文件位于同一目录中的文件,请使用 QCoreApplication::applicationDirPath()
返回所需路径的方法。否则将使用进程工作目录(并不总是可执行目录)。
QFile f(QCoreApplication::applicationDirPath() + "/database.xml");
我猜您没有注意到 Error: file not correctly opened.
警告,是吗?
关于c++ - QDomDocument : setContent() return false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42117178/