解析Xml文件并修改QDomDocument的值

背景:

我需要解決一個bug,需要我從xml中讀取數據到QDomDocument,然后獲取到我想要的目標信息,然后修改該信息。?

---------------------------------------------------------------------------------------------------------

Qt QDomComment讀寫Xml文件(含示例源碼)_qt qdomdocument 操做xml-CSDN博客

QDomDocument類可以方便地讀取和操作XML文件。優點:易于使用XML文檔,缺點是相對較慢。

---------------------------------------------------------------------------------------------------

示例Xml文檔?

XML 教程 | 菜鳥教程 (runoob.com)

<class><student sex="男" age="18"><id>01</id><name>張三</name></student><student sex="女" age="28"><id>02</id><name>李四</name></student>	
</class>

標簽

標簽內包含了要傳遞的信息

它必須成對出現,有開始標簽就需要有結束標簽。

Xml文件必須包含根元素,它是所有其它元素的父元素

XML文檔由元素構成,每個元素包含開始標簽,結束標簽和元素內容。

例如:<id>02</id>

讀取Xml文件的信息

        //XML文件路徑QString path = QCoreApplication::applicationDirPath()+"/xxx.xml";qDebug()<<path;//打開XML文件QFile file(path);if(!file.open(QIODevice::ReadOnly)){qDebug()<<"File open faild!";return-1;}//創建QDomDocument對象,用于解析XMLQDomDocument doc;//通過QFile對象設置QDomDocument的內容if(!doc.setContent(&file)){file.close();return -1;}//關閉文件file.close();//解析XML//獲取XML根結點QDomElement root = doc.documentElement();//遍歷每個student結點//通過標簽名獲取結點列表QDomNodeList studentList = root.elementsByTagName("student");int listSize = studentList.size();for(int i = 0; i < listSize; ++i){//通過索引獲取QDomElement對象QDomElement student = studentList.at(i).toElement();//獲取sex屬性值QString sex = student.attribute("sex");//獲取age屬性值QString age = student.attribute("age");/**函數原型為*QDomElement firstChildElement(const QString &tagName = QString()) const;*解析:參數tagName是可選的,表示要查詢的子元素結點的標簽名。如果指定了tagName,則返回*第一個匹配標簽的子元素結點;如果沒有指定tagName,則返回第一個子元素結點。**/QString studentID = student.firstChildElement("id").text();       //獲取id元素節點的文本內容QString studentName = student.firstChildElement("name").text();   //獲取name元素節點的文本內容qDebug()<<"student:";qDebug()<<"sex:"<<sex;qDebug()<<"age:"<<age;qDebug()<<"studentID:"<<studentID;qDebug()<<"studentName:"<<studentName;}

寫入Xml文件(代碼來自《Qt Creator快速入門》)

QDomDocument doc;QDomProcessingInstruction instruction;instruction = doc.createProcessingInstruction("xml","version = \"1.0\" encoding = \"UTF-8\"");doc.appendChild(instruction);QDomElement root = doc.createElement(QString("書庫"));doc.appendChild(root);QDomElement book = doc.createElement(QString("圖書"));QDomAttr id = doc.createAttribute(QString("編號"));id.setValue("1");book.setAttributeNode(id);QDomText text;QDomElement title = doc.createElement(QString("書名"));text = doc.createTextNode(QString("Qt"));title.appendChild(text);book.appendChild(title);QDomElement author = doc.createElement(QString("作者"));text = doc.createTextNode(QString("shiming"));author.appendChild(text);book.appendChild(author);root.appendChild(book);QFile file("my.xml");if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate))return 0;QTextStream out(&file);doc.save(out,4);file.close();

?

修改書名為《Qt Creator快速入門》 ,作者改為霍亞飛

    //先把信息讀取出來//XML文件路徑QFile file("my.xml");if(!file.open(QIODevice::ReadOnly)){qDebug()<<"File open faild!";return -1;}//創建QDomDocument對象,用于解析XMLQDomDocument doc;//通過QFile對象設置QDomDocument的內容if(!doc.setContent(&file)){file.close();return -1;}//關閉文件file.close();//解析XML//獲取XML根結點QDomElement root = doc.documentElement();QDomElement book = root.firstChildElement("圖書");QDomElement bookName = book.firstChildElement("書名");bookName.firstChild().setNodeValue("Qt Creator快速入門");QDomElement author = book.firstChildElement("霍亞飛");author.firstChild().setNodeValue("sfsefes");if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate))return 0;QTextStream out(&file);doc.save(out,4);file.close();

?

這里我繼續使用Qt的.ui文件作為示例(它是以Xml文件的形式進行存儲的)

<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0"><class>MainWindow</class><widget class="QMainWindow" name="MainWindow"><property name="geometry"><rect><x>0</x><y>0</y><width>731</width><height>460</height></rect></property><property name="windowTitle"><string>Graphics  View繪圖</string></property><widget class="QWidget" name="centralWidget"><widget class="QWGraphicsView" name="View"><property name="geometry"><rect><x>10</x><y>10</y><width>600</width><height>400</height></rect></property><property name="renderHints"><set>QPainter::Antialiasing|QPainter::TextAntialiasing</set></property><property name="dragMode"><enum>QGraphicsView::RubberBandDrag</enum></property></widget></widget><widget class="QMenuBar" name="menuBar"><property name="geometry"><rect><x>0</x><y>0</y><width>731</width><height>30</height></rect></property></widget><widget class="QToolBar" name="mainToolBar"><property name="iconSize"><size><width>16</width><height>16</height></size></property><property name="toolButtonStyle"><enum>Qt::ToolButtonTextUnderIcon</enum></property><attribute name="toolBarArea"><enum>TopToolBarArea</enum></attribute><attribute name="toolBarBreak"><bool>false</bool></attribute><addaction name="actZoomIn"/><addaction name="actZoomOut"/><addaction name="actRestore"/><addaction name="separator"/><addaction name="actRotateLeft"/><addaction name="actRotateRight"/><addaction name="actEdit_Front"/><addaction name="actEdit_Back"/><addaction name="actGroup"/><addaction name="actGroupBreak"/><addaction name="separator"/><addaction name="actEdit_Delete"/><addaction name="separator"/><addaction name="actQuit"/></widget><widget class="QStatusBar" name="statusBar"/><widget class="QToolBar" name="toolBar"><property name="windowTitle"><string>toolBar</string></property><property name="allowedAreas"><set>Qt::LeftToolBarArea</set></property><property name="iconSize"><size><width>16</width><height>16</height></size></property><property name="toolButtonStyle"><enum>Qt::ToolButtonTextUnderIcon</enum></property><attribute name="toolBarArea"><enum>LeftToolBarArea</enum></attribute><attribute name="toolBarBreak"><bool>false</bool></attribute><addaction name="actItem_Rect"/><addaction name="actItem_Ellipse"/><addaction name="actItem_Circle"/><addaction name="actItem_Triangle"/><addaction name="actItem_Polygon"/><addaction name="actItem_Line"/><addaction name="actItem_Text"/></widget><action name="actItem_Rect"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/RECTANGL.BMP</normaloff>:/images/images/RECTANGL.BMP</iconset></property><property name="text"><string>矩形</string></property><property name="toolTip"><string>添加矩形</string></property></action><action name="actItem_Ellipse"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/ELLIPSE.BMP</normaloff>:/images/images/ELLIPSE.BMP</iconset></property><property name="text"><string>橢圓</string></property><property name="toolTip"><string>添加橢圓型</string></property></action><action name="actItem_Line"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/LINE.BMP</normaloff>:/images/images/LINE.BMP</iconset></property><property name="text"><string>直線</string></property><property name="toolTip"><string>添加直線</string></property></action><action name="actEdit_Delete"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/108.bmp</normaloff>:/images/images/108.bmp</iconset></property><property name="text"><string>刪除</string></property><property name="toolTip"><string>刪除選中的圖元</string></property></action><action name="actQuit"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/132.bmp</normaloff>:/images/images/132.bmp</iconset></property><property name="text"><string>退出</string></property><property name="toolTip"><string>退出本系統</string></property></action><action name="actItem_Text"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/800.bmp</normaloff>:/images/images/800.bmp</iconset></property><property name="text"><string>文字</string></property><property name="toolTip"><string>添加文字</string></property></action><action name="actEdit_Front"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/528.bmp</normaloff>:/images/images/528.bmp</iconset></property><property name="text"><string>前置</string></property><property name="toolTip"><string>居于最前面</string></property></action><action name="actEdit_Back"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/526.bmp</normaloff>:/images/images/526.bmp</iconset></property><property name="text"><string>后置</string></property><property name="toolTip"><string>居于最后面</string></property></action><action name="actItem_Polygon"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/FREEFORM.BMP</normaloff>:/images/images/FREEFORM.BMP</iconset></property><property name="text"><string>梯形</string></property><property name="toolTip"><string>添加梯形</string></property></action><action name="actZoomIn"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/zoomin.png</normaloff>:/images/images/zoomin.png</iconset></property><property name="text"><string>放大</string></property><property name="toolTip"><string>放大</string></property></action><action name="actZoomOut"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/zoomout.png</normaloff>:/images/images/zoomout.png</iconset></property><property name="text"><string>縮小</string></property><property name="toolTip"><string>縮小</string></property></action><action name="actRotateLeft"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/rotateleft.png</normaloff>:/images/images/rotateleft.png</iconset></property><property name="text"><string>左旋轉</string></property><property name="toolTip"><string>左旋轉</string></property></action><action name="actRotateRight"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/rotateright.png</normaloff>:/images/images/rotateright.png</iconset></property><property name="text"><string>右旋轉</string></property><property name="toolTip"><string>右旋轉</string></property></action><action name="actRestore"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/420.bmp</normaloff>:/images/images/420.bmp</iconset></property><property name="text"><string>恢復</string></property><property name="toolTip"><string>恢復大小</string></property></action><action name="actGroup"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/UNGROUP.BMP</normaloff>:/images/images/UNGROUP.BMP</iconset></property><property name="text"><string>組合</string></property><property name="toolTip"><string>組合</string></property></action><action name="actGroupBreak"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/128.bmp</normaloff>:/images/images/128.bmp</iconset></property><property name="text"><string>打散</string></property><property name="toolTip"><string>取消組合</string></property></action><action name="actItem_Circle"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/08.JPG</normaloff>:/images/images/08.JPG</iconset></property><property name="text"><string>圓形</string></property><property name="toolTip"><string>圓形</string></property></action><action name="actItem_Triangle"><property name="icon"><iconset resource="res.qrc"><normaloff>:/images/images/Icon1242.ico</normaloff>:/images/images/Icon1242.ico</iconset></property><property name="text"><string>三角形</string></property><property name="toolTip"><string>三角形</string></property></action></widget><layoutdefault spacing="6" margin="11"/><customwidgets><customwidget><class>QWGraphicsView</class><extends>QGraphicsView</extends><header location="global">qwgraphicsview.h</header></customwidget></customwidgets><resources><include location="res.qrc"/></resources><connections><connection><sender>actQuit</sender><signal>triggered()</signal><receiver>MainWindow</receiver><slot>close()</slot><hints><hint type="sourcelabel"><x>-1</x><y>-1</y></hint><hint type="destinationlabel"><x>302</x><y>153</y></hint></hints></connection></connections>
</ui>

還是有難度的。

最外層是標簽ui

內部是

class

widget

layoutdefault

customwidgets

resources

connections

------------------------------------------------

widget內包含

property

widget

action

--------------------------------------------------------

我讀取一下:

  <property name="geometry"><rect><x>0</x><y>0</y><width>731</width><height>460</height></rect></property><property name="windowTitle"><string>Graphics  View繪圖</string></property>

這一段信息吧

讀取.ui文件的代碼

        //解析XMLQDomNode firstNode = doc.firstChild();qDebug()<<"版本和編碼信息:"<<firstNode.nodeName()<<firstNode.nodeValue(); // "xml" "version='1.0' encoding='UTF-8'"qDebug()<<"是否是Xml說明:"<<firstNode.isProcessingInstruction();QDomElement ui = doc.documentElement();qDebug()<<"root tag:"<<ui.tagName();qDebug()<<"root nodeType:"<<ui.nodeType();    //QDomNode::ElementNode	1qDebug()<<"root hasChildNodes:"<<ui.hasChildNodes();    //trueqDebug()<<"root childNodes count:"<<ui.childNodes().count();    //6qDebug()<<"root hasAttributes:"<<ui.hasAttributes();    //trueqDebug()<<"root hasAttribute version:"<<ui.hasAttribute("version"); //trueQDomElement xWidget = ui.firstChildElement("widget");qDebug()<<"widget hasAttribute name:"<<xWidget.hasAttribute("name");    //trueqDebug()<<"widget hasAttribute class:"<<xWidget.hasAttribute("class");  //trueQDomElement xProperty = xWidget.firstChildElement("property");while(!xProperty.isNull()){qDebug()<<xProperty.attribute("name");xProperty = xProperty.nextSiblingElement("property");}

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

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

相關文章

各大常用代碼編輯器的快捷鍵集合

visualstudio2017 快捷鍵 多行注釋 crtl / 取消多行注釋crtl Q 代碼跳轉返回 crtl /- visualcode快捷鍵 代碼跳轉返回 crtl 左鍵/右鍵 androidstudio快捷鍵 代碼跳轉返回 crtl alt 左鍵/右鍵

VUE中ECharts提示框tooltip自動切換

目錄 前言1導入插件2定義參數3 插件API 前言 使用VUE開發的數據大屏統計&#xff0c;又需要將 echarts的提示框 tooltip 實現自動切換&#xff0c;網上有個很簡單的插件&#xff08;echarts-tooltip-auto-show&#xff09;&#xff0c;使用教程簡單分享給大家。 自動每隔幾秒切…

哦華為倉頡語言

本來我不太想說的&#xff0c;奈何有不少粉絲提問提到了這語言&#xff0c;目前的情況我不透露太多&#xff0c;看過這課程C實現一門計算機編程語言到手擼虛擬機實戰的懂的自然懂。 在互聯網領域幾乎大部分應用軟件運行在X86 LINUX上居多&#xff0c;如果你有問題可以先學習這…

多版本python環境中,讓python3固定指向其中一個python可執行文件

如果你只安裝一個python環境&#xff0c;那么一般可執行文件名就叫python.exe和pythonw.exe 但是如果你有多個python環境時&#xff0c;可執行文件名是需要進行修改的&#xff0c;使得在安裝庫和調用時能夠分辨python環境&#xff0c;比如我的電腦中裝有python3.10和python2.x …

Transformer模型論文解讀、源碼分析和項目實踐

本文是ChatGPT系列的開篇之作&#xff0c;為什么吧Transformer放到這里呢&#xff0c;因為不管是chatgpt-1&#xff0c; chatgpt-2&#xff0c; chatgpt-3都是以Transformer作為底層基礎來實現&#xff0c;相當于chatgpt系列的老祖先了。如果想要深入的了解清楚chatgpt的來龍去…

AcWing 4173. 線段 (貪心)

數軸上有 n 條線段&#xff0c;選取其中 k 條線段使得這 k&#x1d458; 條線段兩兩沒有重合部分&#xff0c;問 k 最大為多少。 輸入格式 第一行為一個正整數 n&#xff1b; 在接下來的 n 行中&#xff0c;每行有 2 個數 ai,bi&#xff0c;描述每條線段的左右端點坐標。 輸…

BUUCTF[堆][of_by_one]

堆中of_by_one 介紹&#xff1a; 嚴格來說 off-by-one 漏洞是一種特殊的溢出漏洞&#xff0c;off-by-one 指程序向緩沖區中寫入時&#xff0c;寫入的字節數超過了這個緩沖區本身所申請的字節數并且只越界了一個字節。溢出字節為可控制任意字節 &#xff1a;通過修改大小(size…

token無感刷新方法

1.這里推薦去看這個老師的視頻,我的方案都是根據他的視頻來的視頻地址 2.這邊使用的工具是axios import axios from axios const service axios.create({baseURL: ,headers: {Authorization: token 你自己的token,},timeout: 1000 * 60, })// 攔截響應 service.interceptors…

Spring AOP源碼篇四之 數據庫事務

了解了Spring AOP執行過程&#xff0c;再看Spring事務源碼其實非常簡單。 首先從簡單使用開始, 演示Spring事務使用過程 Xml配置&#xff1a; <?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema…

【北京迅為】《i.MX8MM嵌入式Linux開發指南》-第一篇 嵌入式Linux入門篇-第十六章 Linux 第一個程序 HelloWorld

i.MX8MM處理器采用了先進的14LPCFinFET工藝&#xff0c;提供更快的速度和更高的電源效率;四核Cortex-A53&#xff0c;單核Cortex-M4&#xff0c;多達五個內核 &#xff0c;主頻高達1.8GHz&#xff0c;2G DDR4內存、8G EMMC存儲。千兆工業級以太網、MIPI-DSI、USB HOST、WIFI/BT…

S271系列RTU在旅游景區人流監控中的應用案例

S271系列RTU在旅游景區人流監控中的應用案例 隨著全球旅游業的迅猛發展&#xff0c;旅游景區的管理者越來越關注如何利用先進的技術手段提升游客體驗、優化管理效率以及確保安全。S271系列RTU作為一款先進的無線工業物聯網設備&#xff0c;在旅游景區的人流監控中展現出了其獨…

數據結構:順序表+鏈表

數據結構&#xff1a;順序表鏈表 一。順序表&#xff1a; 首先在了解順序表和鏈表之前&#xff0c;先了解一下線性表&#xff0c;**線性表&#xff08;linear list&#xff09;**是n個具有相同特征元素的有限序列 &#xff0c;在邏輯上是線性結構&#xff0c;也就是一條連續的…

自動化升級:Conda包依賴的智能更新策略

自動化升級&#xff1a;Conda包依賴的智能更新策略 引言 在科學研究和軟件開發中&#xff0c;依賴管理是確保項目順利進行的關鍵環節。Conda作為流行的包管理器&#xff0c;提供了強大的依賴更新功能&#xff0c;幫助用戶自動化和簡化依賴項的更新過程。本文將深入探討如何在…

WPF依賴附加屬性

依賴附加屬性的定義 基本過程&#xff1a;聲明、注冊、包裝 依賴附加屬性必須在依賴對象&#xff0c;附加屬性不一定&#xff0c;關注的是被附加的對象是否是依賴對象 快捷方式&#xff1a;propa tab 關鍵字&#xff1a;RegisterAttached // 方法封裝 public static int …

Unity3d C#實現基于UGUI ScrollRect的輪播圖效果功能(含源碼)

前言 輪播功能是一種常見的頁面組件&#xff0c;用于在頁面中顯示多張圖片/素材并自動或手動進行切換&#xff0c;以提高頁面的美觀度和用戶體驗。主要的功能是&#xff1a;自動/手動切換;平滑的切換效果;導航指示器等。可惜Unity的UGUI系統里沒有現成的實現該功能&#xff0c…

第五次作業(多表聯合查詢)

新增員工表emp和部門表dept create table dept (dept1 int ,dept_name varchar(11)) charsetutf8; create table emp (sid int ,name varchar(11),age int,worktime_start date,incoming int,dept2 int) charsetutf8; insert into dept values (101,財務), (102,銷售…

Shell學習——Shell echo命令

文章目錄 echo命令 echo命令 1.顯示普通字符串: echo "It is a test"這里的雙引號完全可以省略&#xff0c;以下命令與上面實例效果一致&#xff1a; echo It is a test2.顯示轉義字符 echo "\"It is a test\""結果將是: "It is a tes…

掌握MOJO命令行:參數解析的藝術

在軟件開發中&#xff0c;命令行接口&#xff08;CLI&#xff09;是一種與程序交互的強大方式&#xff0c;它允許用戶通過終端輸入指令和參數來控制程序的行為。對于MOJO語言&#xff0c;即使它是一個假想的編程語言&#xff0c;我們也可以設想它具備解析命令行參數的能力。本文…

初識C++【命名空間】【輸入輸出】【缺省參數】【函數重載】

前言 C是一種通用的編程語言&#xff0c;被廣泛用于開發各種應用程序&#xff0c;包括系統軟件、游戲、手機應用和高性能計算等。它是C語言的擴展&#xff0c;添加了許多新特性和功能&#xff0c;并支持面向對象編程。C可以在不同的平臺上編譯和運行&#xff0c;具有高效性、可…

開放式耳機哪個品牌比較好?2024最值得推薦的火爆機型!!

在這個快節奏的時代&#xff0c;我們都在尋找那些既能讓我們享受音樂&#xff0c;又能保持對外界感知的音頻設備。開放式耳機以其獨特的設計&#xff0c;滿足了這一需求&#xff0c;它們讓你在享受音樂的同時&#xff0c;還能聽到周圍環境的聲音&#xff0c;無論是安全出行還是…