1. 功能
將A.xml
文件中的copyNode
節點全部復制到B.xml
中的testRoot
節點。
2. 代碼
#include <QDomDocument>
#include <QFile>
#include <QIODevice>
#include <QtXml>void copyNodeXml()
{// 源文件DOMQDomDocument ADoc;// 加載源文件QFile fileA("A.xml");if (!fileA.open(QIODevice::ReadOnly)) {// 錯誤處理}if (!ADoc.setContent(&fileA)) {// 錯誤處理}fileA.close();/************************************************************///目的DOMQDomDocument BDoc;//目的文件QFile fileB("B.xml");if(!fileB.open(QFile::WriteOnly | QFile::Truncate)){// 錯誤處理}/************************************************************///創建XML頭部格式QDomProcessingInstruction instruction;instruction = BDoc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\"");BDoc.appendChild(instruction);//添加根節點QDomElement root = BDoc.createElement("testRoot");BDoc.appendChild(root);/************************************************************///開始復制QDomNode methodOriginal = ADoc.elementsByTagName("copyNode").at(0);QDomNode newNode = methodOriginal.cloneNode(true); //遞歸復制root.appendChild(newNode);/************************************************************///保存QTextStream out_stream(&fileB);BDoc.save(out_stream, 4);fileB.close();}