QT DOM方式寫入xml檔案
阿新 • • 發佈:2019-02-06
依賴的標頭檔案:
#include <QFile>
#include <QString>
#include <QtXml>
#include <QDomDocument>
#include <QDateTime>
示例程式碼:
//寫xml操作。sXmlFilePath:要寫入的xml檔案路徑 int CAppletGenerator::addTaskMenuTreeItem(QString sXmlFilePath) { QFile file(sXmlFilePath); if (!file.open(QFile::ReadOnly | QFile::Text)) { return -1; } QDomDocument domDocument; if (!domDocument.setContent(&file, true)) { file.close(); return -1; } QDomElement tree = domDocument.documentElement(); QDomElement firstItem = tree.firstChildElement(); //在firstitem上新增一個節點 QDomElement secondItem = domDocument.createElement("item"); //獲取當前時間,用於節點的唯一性id QDateTime dt; QTime time; QDate date; dt.setTime(time.currentTime()); dt.setDate(date.currentDate()); QString currentDate = dt.toString("yyyyMMddhhmmss"); //為節點新增屬性 secondItem.setAttribute("id",currentDate); secondItem.setAttribute("select","1"); secondItem.setAttribute("text","節點"); //新增元素節點到父節點 firstItem.appendChild(secondItem); file.close(); QFile fileModify(sXmlFilePath); if (!fileModify.open(QFile::WriteOnly | QFile::Text)){ return -1; } //核心程式碼:Dom方式寫xml檔案 QTextStream out(&fileModify); domDocument.save(out,4); fileModify.close(); return 0; }