Qt的Xml操作QDomDocument

Qt的Xml操作QDomDocument

Qt對于Xml的支持是很好的,一些我們需要的操作應有盡有,下面簡單介紹一下怎樣使用。主要有以下幾點使用:

  1. 寫xml到文件
  2. 讀xml
  3. 添加節點到xml
  4. 刪除xml中某節點信息
  5. 修改xml中某節點信息

準備工作

  1. .pro加入QT += xml
  2. 需要include QDomDocument QTextStream QFile三個頭文件

WriteXml

直接上代碼

void writeXml()
{QDomDocument doc;QDomProcessingInstruction xmlInstruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"");QDomComment comment = doc.createComment(QString::fromLocal8Bit("離開是為了更好的歸來"));QDomProcessingInstruction styleInstruction = doc.createProcessingInstruction("xml-stylesheet", "type=\"text/css\" href=\"style.css\"");doc.appendChild(xmlInstruction);  // 開始文檔(XML 聲明)doc.appendChild(comment);  // 注釋doc.appendChild(styleInstruction);  // 處理指令// 根元素 <Blogs>QDomElement root = doc.createElement("Books");root.setAttribute("Version", "1.0");  // 屬性doc.appendChild(root);// 元素 <Blog>QDomElement child = doc.createElement("Book");root.appendChild(child);// 元素 <作者>、<時間>、<個人說明>QDomElement author = doc.createElement(QString::fromLocal8Bit("作者"));QDomElement home = doc.createElement(QString::fromLocal8Bit("時間"));QDomElement instruction = doc.createElement(QString::fromLocal8Bit("個人說明"));child.appendChild(author);child.appendChild(home);child.appendChild(instruction);// 元素的文本數據QDomText authorText = doc.createTextNode(QString::fromLocal8Bit("Vincent"));QDomText homeText = doc.createTextNode("2017年4月13日");QDomText instructionText = doc.createTextNode(QString::fromLocal8Bit("大宋樞密院常任委員會_委員"));author.appendChild(authorText);home.appendChild(homeText);instruction.appendChild(instructionText);// 保存 XML 文件QString strFile("Books.xml");QFile file(strFile);// 只寫模式打開文件if (file.open(QFile::WriteOnly | QFile::Text)){QTextStream out(&file);doc.save(out, QDomNode::EncodingFromDocument);file.close();}
}
void writeXML()
{//打開或創建文件QString fileName{"test.xml"};QFile file(fileName);//QIODevice::Truncate表示清空原來的內容if(!file.open(QFile::WriteOnly|QFile::Truncate))return;//創建xml文檔在內存中QDomDocument doc;//添加處理命令QDomProcessingInstruction instruction;instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"");//創建注釋QDomComment comment;comment = doc.createComment(QString::fromLocal8Bit("離開是為了更好的歸來"));QDomProcessingInstruction styleInstruction;styleInstruction= doc.createProcessingInstruction("xml-stylesheet", "type=\"text/css\" href=\"style.css\"");doc.appendChild(instruction); //文檔開始聲明doc.appendChild(comment);doc.appendChild(styleInstruction);  // 處理指令//添加根節點QDomElement root=doc.createElement("library");root.setAttribute("Version","2.1");doc.appendChild(root);//添加第一個子節點及其子元素QDomElement book=doc.createElement("book");//方式一:創建屬性  其中鍵值對的值可以是各種類型book.setAttribute("id",1);//方式二:創建屬性 值必須是字符串QDomAttr time=doc.createAttribute("time");time.setValue("2013/6/13");book.setAttributeNode(time);QDomElement title=doc.createElement("title"); //創建子元素QDomText text; //設置括號標簽中間的值text=doc.createTextNode("C++ primer");book.appendChild(title);title.appendChild(text);QDomElement author=doc.createElement("author"); //創建子元素text=doc.createTextNode("Stanley Lippman");author.appendChild(text);book.appendChild(author);//添加節點book做為根節點的子節點root.appendChild(book);//添加第二個子節點及其子元素book=doc.createElement("book");book.setAttribute("id",2);time=doc.createAttribute("time");time.setValue("2007/5/25");book.setAttributeNode(time);title=doc.createElement("title");text=doc.createTextNode("Thinking in Java");book.appendChild(title);title.appendChild(text);author=doc.createElement("author");text=doc.createTextNode("Bruce Eckel");author.appendChild(text);book.appendChild(author);root.appendChild(book);//輸出到文件QTextStream out_stream(&file);doc.save(out_stream,4); //縮進4格file.close();
}

ReadXml

上代碼

void readXML()
{//打開或創建文件QFile file("test.xml");if(!file.open(QFile::ReadOnly))return;QDomDocument doc;//設置wangfei1.xml到文檔if(!doc.setContent(&file)){file.close();return;}file.close();//返回根節點QDomElement root=doc.documentElement();qDebug()<<root.nodeName();//如果xml根元素有屬性(Version)將輸出,Vinsion是用戶自定義的屬性,沒有繼續執行下一條命令if (root.hasAttribute("Version"))  // 屬性qDebug() << root.attribute("Version");/**********根元素之上(XML 聲明、注釋等)**********/QDomNode node = root.previousSibling();while (!node.isNull()){switch (node.nodeType()){case QDomNode::ProcessingInstructionNode :{QDomProcessingInstruction instruction = node.toProcessingInstruction();//輸出處理指令,是用戶自定義的,比如字符串“name”對應處理指令得到名字,這個命令是用戶寫的qDebug() << instruction.target() << instruction.data();if (QString::compare(instruction.target(), "xml") == 0) // 開始文檔(XML 聲明){//cout<<"處理命令xml"<<endl;// ...}else if (QString::compare(instruction.target(), "xml-stylesheet") == 0) // 處理指令{//cout<<"處理命令xml-stylesheet"<<endl;// ...}break;}case QDomNode::CommentNode :{QDomComment comment = node.toComment();qDebug() << comment.data();break;}default:break;}node = node.previousSibling();}//獲得第一個子節點node=root.firstChild();while(!node.isNull())  //如果節點不空{if(node.isElement()) //如果節點是元素{//轉換為元素QDomElement element=node.toElement();if (!element.isNull())// 節點的確是一個元素{//輸出第一個節點,包括第一個節點的屬性,這個屬性需要指定屬性值,才能輸出,如果沒有輸出空qDebug()<<element.tagName()<<" "<<element.attribute("id")<<" "<<element.attribute("time");QDomNodeList list=element.childNodes();for(int i=0;i<list.count();++i){QDomNode n=list.at(i);//node = list.at(i);if(node.isElement()){qDebug()<<n.nodeName()<<":"<<n.toElement().text();element = n.toElement();//qDebug()<<element.nodeName()<<":"<<element.toElement().text();if (QString::compare(element.tagName(), QStringLiteral("作者")) == 0){// ...處理命令//cout<< "處理命令作者"<<endl;}else if (QString::compare(element.tagName(), QStringLiteral("時間")) == 0){//cout<<"處理命令時間"<<endl;// ...處理命令}else if (QString::compare(element.tagName(), QStringLiteral("個人說明")) == 0){//cout<<"處理命令個人說明"<<endl;// ...處理命令}}}}}//下一個兄弟節點node=node.nextSibling();}
}

AddXml

void addXML()
{//打開文件QFile file("test.xml");if(!file.open(QFile::ReadOnly))return;//增加一個一級子節點以及元素QDomDocument doc;if(!doc.setContent(&file)){file.close();return;}file.close();//創建根節點QDomElement root = doc.documentElement();//創建next子節點bookQDomElement book = doc.createElement("book");book.setAttribute("id",3);book.setAttribute("time","1813/1/27");QDomElement title = doc.createElement("title");QDomText text;text = doc.createTextNode("Pride and Prejudice");//添加text內容到title節點title.appendChild(text);//添加title到book節點book.appendChild(title);//添加book到根節點root.appendChild(book);if(!file.open(QFile::WriteOnly|QFile::Truncate))return;//輸出到文件QTextStream out_stream(&file);doc.save(out_stream,4); //以縮進4格方式輸出,也有其他輸出方式(格式)file.close();
}

DeleteXml

void deleteXML()
{//打開文件QFile file("test.xml");if(!file.open(QFile::ReadOnly))return;//刪除一個一級子節點及其元素,外層節點刪除內層節點于此相同QDomDocument doc;if(!doc.setContent(&file)){file.close();return;}file.close();QDomElement root=doc.documentElement();//由標簽名定位,本標簽為book,以后可以是用string類型的字符串替換,實現動態QDomNodeList list=doc.elementsByTagName("book");//刪除方式一,通過標簽book后面的屬性刪除<book>到</book>for(int i=0;i<list.count();i++){//轉化為元素QDomElement e=list.at(i).toElement();//找到time是2007/5/25這一條數據將其刪除if(e.attribute("time")=="2007/5/25")root.removeChild(list.at(i));}//刪除方式二,可以通過索引直接刪除
//    root.removeChild(list.at(1));if(!file.open(QFile::WriteOnly|QFile::Truncate))return;//輸出到文件QTextStream out_stream(&file);doc.save(out_stream,4); //縮進4格file.close();
}

AmendXml

void amendXML()
{//打開文件QFile file("wangfei1.xml");if(!file.open(QFile::ReadOnly))return;//更新一個標簽項,如果知道xml的結構,直接定位到那個標簽上定點更新//或者用遍歷的方法去匹配tagname或者attribut,value來更新QDomDocument doc;//設置wangfei.xml讀到doc文檔if(!doc.setContent(&file)){file.close();return;}file.close();/***    知道xml結構,直接定位修改*   提取根節點**/QDomElement root=doc.documentElement();//以book標簽存入list
//    QDomNodeList list=root.elementsByTagName("book");
//    QDomNode listNode=list.at(list.size()-2).firstChild();
//    QDomNode oldnode=listNode.firstChild();
//    //把title改成Emma
//    listNode.firstChild().setNodeValue("aaaaaaa");
//    QDomNode newnode=listNode.firstChild();
//    listNode.replaceChild(newnode,oldnode);//使用遍歷方法選擇要修改的元素
//    QDomNodeList lists =doc.childNodes();
//    QDomNodeList list=root.elementsByTagName("book");QDomNode node = root.firstChild();//QDomNodeList list=root.elementsByTagName("book");while(!node.isNull())  //如果節點不空{if(node.isElement()) //如果節點是元素{//轉換為元素QDomElement element=node.toElement();if (!element.isNull() && element.attribute("id") == "3")// 節點的確是一個元素{//輸出第一個節點,包括第一個節點的屬性,這個屬性需要指定屬性值,才能輸出,如果沒有輸出空//qDebug()<<element.tagName()<<" "<<element.attribute("id")<<" "<<element.attribute("time");QDomNodeList list=element.childNodes();for(int i=0;i<list.count();++i){QDomNode n=list.at(i);//node = list.at(i);if(node.isElement()){//qDebug()<<n.nodeName()<<":"<<n.toElement().text();element = n.toElement();//與上面qDebug效果相同//qDebug()<<element.nodeName()<<":"<<element.toElement().text();//這個if可以不需要,如果需要精確定位,以防數據相同所以要加這個嵌套ifif (QString::compare(element.tagName(), QStringLiteral("title")) == 0){if("Pride and Prejudice" == element.toElement().text()){// ...處理命令,在這個if里可以遍歷想要的節點進行修改//新建一個舊的node緩存QDomNode oldNode = n.firstChild();n.firstChild().setNodeValue("changchun1");//新建一個新的newNode子節點QDomNode newNode = n.firstChild();//使用replaceChild替換noden.replaceChild(newNode,oldNode);}}else if (QString::compare(element.tagName(), QStringLiteral("時間")) == 0){//cout<<"處理命令時間"<<endl;// ...處理命令}else if (QString::compare(element.tagName(), QStringLiteral("個人說明")) == 0){//cout<<"處理命令個人說明"<<endl;// ...處理命令}}}}}//下一個兄弟節點node=node.nextSibling();}if(!file.open(QFile::WriteOnly|QFile::Truncate))return;//輸出到文件QTextStream out_stream(&file);doc.save(out_stream,4); //縮進4格file.close();}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/536189.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/536189.shtml
英文地址,請注明出處:http://en.pswp.cn/news/536189.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

2815:城堡問題

2815:城堡問題 查看提交統計提示提問 總時間限制: 1000ms 內存限制: 65536kB描述1 2 3 4 5 6 7 #############################1 # | # | # | | ######---#####---#---#####---#2 # # | # # # # ##---#####---#####---#####---#3 # …

冒泡排序法函數

文章目錄冒泡排序法的函數實現使用教程冒泡排序法的函數實現 話不多說上代碼&#xff0c;拿去直接用。 // 冒泡排序函數 /* * brief sort * param array為數組名稱&#xff0c;length為數組的長度&#xff0c;order為1或0,1代表從小到大排序 * 0代表從大到小排序…

boost序列化(Serialization)

本文章轉載自 http://m.blog.csdn.net/zj510/article/details/8105408 程序開發中&#xff0c;序列化是經常需要用到的。像一些相對高級語言&#xff0c;比如JAVA, C#都已經很好的支持了序列化&#xff0c;那么C呢&#xff1f;當然一個比較好的選擇就是用Boost&#xff0c;這個…

java基礎經典練習題

【程序1】 題目&#xff1a;古典問題&#xff1a;有一對兔子&#xff0c;從出生后第3個月起每個月都生一對兔子&#xff0c;小兔子長到第三個月后每個月又生一對兔子&#xff0c;假如兔子都不死&#xff0c;問每個月的兔子總數為多少&#xff1f; //這是一個菲波拉契數列問題 p…

ubuntu下wps不能輸入中文

ubuntu下wps不能輸入中文 原因是因為fcitx環境的原因&#xff0c;想了解fcitx的可以看這篇文章&#xff0c;鏈接。 使用腳本解決 將下面的腳本復制到新建的文件中&#xff0c;chmod加權限&#xff0c;然后執行即可。 #! /bin/bash #--------------------------------------…

常見的幾種內排序算法以及實現(C語言)(轉)

所有未排序的數組是經過檢查合法的主要的內排序包括冒泡、插入、希爾、堆排序、歸并、快速、桶排序等其C語言實現的源文件下載地址&#xff1a;http://download.csdn.net/detail/mcu_tian/9530227冒泡排序冒泡排序應該是排序中最簡單的算法了主要思路如下&#xff1a;1&#xf…

常見編程命名縮寫

命名縮寫 通用縮寫翻譯控件縮寫翻譯addressaddr地址calendarcdr日歷applicationapp應用程序messageDialogmsgdlg消息框asynchronizationasyn異步drawerdrw抽屜averageavg平均數buttonGroupbtngrp按鈕分組bitmapbmp位圖checkBoxchk復選框bufferbuf緩沖區containercntr容器chara…

funCode課程實訓(C++ )

funcode是一個簡單的游戲制作引擎&#xff0c;適合c初學者操作&#xff0c;可以幫助初學者更好的了解c環境&#xff0c;以及各種函數的實現&#xff0c;本學期我們用funcode作為C最后的課程設計&#xff0c;所以我就使用funcode制作一個打地鼠的小游戲。以下是對這個小程序的描…

Nodejs,Npm,React安裝教程

React安裝 1.下載node.js安裝包 下載二進制包 選擇比較穩定的版本進行安裝&#xff0c;v8.9 2.安裝 直接把文件解壓復制到某個目錄下&#xff0c; sudo cp -r node-v8.9.0 /opt/node #你下載的版本sudo touch /etc/profile.d/node.sh #新建一個腳本文件sudo gedit /etc/…

Ubuntu下的提示信息彩色顯示

【問題】 雖然已經折騰過了&#xff1a; 【已解決】Ubuntu中讓終端只顯示當前路徑&#xff0c;而不顯示絕對路徑 但是&#xff0c;終端中的prompt提示信息&#xff0c;不是彩色的&#xff0c;導致的結果是&#xff1a; 當終端中輸出信息很多時&#xff1a; 【已解決】Ubun…

hustoj的搭建

最近開始接觸服務器之類的&#xff0c;就自己搭建一個hustoj的服務器&#xff0c;hustoj系統的搭建在網上已經很完善了&#xff0c;這里我就簡單的說一下&#xff0c;作為自己的學習筆記。 安裝主要環境&#xff0c;Apache2&#xff0c;MySQL&#xff0c;php5和PHPmyadmin。 …

Shell字符串操作集合

字符操作字符串的長度獲取字符串中某些字符的個數統計單詞的個數bash提供的數組數據結構它是以數字為下標的和C語言從0開始的下一樣awk里面的數組取子串匹配求子串sed有按行打印的功能記得用tr把空格換為行號tr來取子串head和tail查詢字串子串替換tac 會將文本的內容倒置顯示正…

百練4982 踩方格

總時間限制: 1000ms 內存限制: 65536kB描述有一個方格矩陣&#xff0c;矩陣邊界在無窮遠處。我們做如下假設&#xff1a;a. 每走一步時&#xff0c;只能從當前方格移動一格&#xff0c;走到某個相鄰的方格上&#xff1b;b. 走過的格子立即塌陷無法再走第二次&#xff1b;…

Qt自定義QML模塊

自定義QML模塊 含義為將常用風格的Button&#xff0c;Text,RadioButton,或者自定義的控件作為一個控件進行使用&#xff0c;節省代碼。 優點&#xff1a; 代碼簡潔&#xff0c;減少重復代碼自定義的控件進行封裝重復使用可以與QML自帶的庫區別開來優化項目結構 一、創建模塊…

POJ3984 迷宮問題【BFS】

好長時間沒有敲過代碼了&#xff0c;感覺之前學過的都忘了&#xff0c;趁著這個暑假&#xff0c;打算把之前學習的東西都復習一下&#xff0c;當然得慢慢來&#xff0c;畢竟好長時間不敲代碼了&#xff0c;怎么著都有些生疏&#xff0c;再加上之前學的也不咋地&#xff0c;相當…

宏定義基本用法

宏定義 不帶參數 宏定義又稱為宏代換、宏替換&#xff0c;簡稱“宏”。 格式&#xff1a; #define 標識符 字符串其中的標識符就是所謂的符號常量&#xff0c;也稱為“宏名”。 預處理&#xff08;預編譯&#xff09;工作也叫做宏展開&#xff1a;將宏名替換為字符串。 掌…

廣度優先搜索練習之神奇的電梯

廣度優先搜索練習之神奇的電梯 Time Limit: 1000ms Memory limit: 65536K 題目描述 有一座已知層數為n的高樓&#xff0c;這座高樓的特殊之處在于只能靠電梯去上下樓&#xff0c;所以要去到某一層要非常耽誤時間&#xff0c;然而更悲哀的是&#xff0c;這座高樓的電梯是限號…

ubuntu安裝proxychains及自動補全

proxychains ProxyChains是本人目前為止用到的最方便的代理工具。 inux下代理一般是通過http_proxy和https_proxy這兩個環境變量&#xff0c;但是很多軟件并不使用這兩個變量&#xff0c;導致流量無法走代理。在不使用vpn的前提下&#xff0c;linux并沒有轉發所有流量的真全局…

快速冪講解

快速冪的目的就是做到快速求冪&#xff0c;假設我們要求a^b,按照樸素算法就是把a連乘b次&#xff0c;這樣一來時間復雜度是O(b)也即是O(n)級別&#xff0c;快速冪能做到O(logn)&#xff0c;快了好多好多。它的原理如下&#xff1a; 假設我們要求a^b&#xff0c;那么其實b是可以…

如何查詢資料

如何查詢資料技術資料及問題查詢查詢方法分類查找提取關鍵字GitHub項目優先使用Google搜索引擎Copy Paste論文查找詢問主管 測試修改使用總結分享 公司信息查詢國內公司國外公司 如何查詢資料 技術資料及問題查詢 查詢方法 資料與解決辦法的查詢大致分為7大類。 1.分類查…