【问题标题】:Update XML file in QT在 QT 中更新 XML 文件
【发布时间】:2012-09-28 10:03:02
【问题描述】:

我有 XML 文件

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

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

【问题讨论】:

    标签: xml qt xml-parsing


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-18
      • 2011-03-06
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      相关资源
      最近更新 更多