在QT中更新XML文件

7
我有一个 XML 文件。
<root rootname="RName" otherstuff="temp">
     <somechild childname="CName" otherstuff="temp">
     </somechild>
</root>

在上述XML中,我如何使用QT将 RName 更新为 RN,并将CName更新为CN?我正在使用QDomDocument,但无法完成所需的操作。
1个回答

16

如果您分享一下使用QDomDocument的情况以及具体哪个部分有问题,那将会很有帮助。但以下是一般情况:

  • 从文件系统读取文件;

  • 将文件解析为QDomDocument;

  • 修改文档内容;

  • 将数据保存回文件。

在Qt代码中:

// Open file
QDomDocument doc("mydocument");
QFile file("mydocument.xml");
if (!file.open(QIODevice::ReadOnly)) {
    qError("Cannot open the file");
    return;
}
// Parse file
if (!doc.setContent(&file)) {
   qError("Cannot parse the content");
   file.close();
   return;
}
file.close();

// Modify content
QDomNodeList roots = elementsByTagName("root");
if (roots.size() < 1) {
   qError("Cannot find root");
   return;
}
QDomElement root = roots.at(0).toElement();
root.setAttribute("rootname", "RN");
// Then do the same thing for somechild
...

// Save content back to the file
if (!file.open(QIODevice::Truncate | QIODevice::WriteOnly)) {
    qError("Basically, now we lost content of a file");
    return;
}
QByteArray xml = doc.toByteArray();
file.write(xml);
file.close();

注意,在实际应用中,你需要将数据保存到另一个文件中,确保保存成功后再用副本替换原始文件。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接