gpt4 book ai didi

xml - 在 QT 中更新 XML 文件

转载 作者:数据小太阳 更新时间:2023-10-29 01:49:19 27 4
gpt4 key购买 nike

我有Xml文件

<root rootname="RName" otherstuff="temp">
<somechild childname="CName" otherstuff="temp">
</somechild>
</root>

在上面的 XML 中,如何使用 QT 将 RName 更新为 RN 并将 CName 更新为 CN。我正在使用 QDomDocument 但无法执行所需的操作。

最佳答案

如果您分享您如何使用 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();

请注意,在现实生活中的应用程序中,您会希望将数据保存到另一个文件,确保保存成功,然后用副本替换原始文件。

关于xml - 在 QT 中更新 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12637858/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com