生活随笔
收集整理的這篇文章主要介紹了
Qt中DOM的读写
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
?對(duì)于一般的XML數(shù)據(jù)處理,Qt提供了QtXml模塊。QXml模塊提供了三種截然不同的應(yīng)用程序編程接口用于讀取XML文檔:
? ?????QXmlStreamReader 是一個(gè)用于讀取格式良好的XML文檔的快速解析器。
? ? ????DOM(文檔對(duì)象模型)把XML文檔轉(zhuǎn)換為應(yīng)用程序可以遍歷的樹形結(jié)構(gòu)。
? ? ????SAX(XML簡(jiǎn)單應(yīng)用程序編程接口)通過(guò)虛擬函數(shù)直接向應(yīng)用程序報(bào)告“解析事件”。
? ? 對(duì)于XML文件的寫入,Qt也提供了三種可用的方法:
????? ? 使用QXmlStreamWriter。
?
在內(nèi)存中以DOM樹的結(jié)構(gòu)表示數(shù)據(jù),并要求這個(gè)數(shù)型結(jié)構(gòu)將自己寫到文件中。
????? ? 手動(dòng)生成XML。
在這里我使用了DOM來(lái)對(duì)XML文件進(jìn)行操作,代碼如下:
生成的樹形結(jié)構(gòu)如下:
<?xml?version?="1.0"?encoding="UTF-8"?>?<ContactMan>?????<Info>?????????<name>zhang?san</name>?????????<phone>110119120</phone>?????</Info>?</ContactMan>????bool?RWXml::readFile(const?QString?&fileName)?{?????QFile?file(fileName);?????if(!file.open(QFile::ReadOnly?|?QFile::Text))?????{?????????std::cerr?<<?"Error:?Cannot?read?file"?<<std::endl;?????????return?false;?????}?????QString?errorStr;?????int?errorLine;?????int?errorColumn;?????QDomDocument?doc;??????if(!doc.setContent(&file,true,&errorStr,&errorLine,&errorColumn))?????{?????????std::cerr?<<?"Error:?Prase?error?at?line?"?<<?std::endl;?????????file.close();?????????return?false;?????}?????QDomElement?root?=?doc.documentElement();?????QDomNode?n?=?root.firstChild();?????while(!n.isNull())?????{?????????QDomElement?e=?n.toElement();?????????if(!e.isNull())?????????{?????????????qDebug()?<<?e.tagName()?<<?":"?<<?e.text();?????????}?????????n?=?n.nextSibling();?????}??????file.close();;?????return?true;?}?bool?RWXml::writeFile(const?QString?&fileName)?{?????QFile?file(fileName);?????if(!file.open(QFile::Text?|?QFile::WriteOnly))?????{?????????std::cerr?<<?"Error:?Cannot?write?file"?<<?qPrintable(fileName)?<<?std::endl;??????????file.close();??????????return?false;?????}?????QDomDocument?doc;?????QDomProcessingInstruction?instruction;?????instruction?=?doc.createProcessingInstruction("xml"?,?"version?=\"1.0\"?encoding=\"UTF-8\"");?????doc.appendChild(instruction);?????QDomElement?root?=?doc.createElement("ContactMan");?????doc.appendChild(root);??????QDomElement?info_Node?=?doc.createElement("Info");???????????????????QDomElement?name_Node?=?doc.createElement("name");?????QDomElement?phone_Node?=?doc.createElement("phone");??????QDomText?text;?????text?=?doc.createTextNode("zhang?san");?????name_Node.appendChild(text);?????text?=?doc.createTextNode("110119120");?????phone_Node.appendChild(text);??????info_Node.appendChild(name_Node);?????info_Node.appendChild(phone_Node);??????root.appendChild(info_Node);??????QTextStream?out(&file);?????doc.save(out?,?4);?????file.close();?????return?true;?}? ?
轉(zhuǎn)載于:https://blog.51cto.com/mjrao/1007951
總結(jié)
以上是生活随笔為你收集整理的Qt中DOM的读写的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。