一、xml說明:
1.被設計用來傳輸和存儲數據,是一種可擴展標記語言,能夠實現跨系統傳輸數據。
2.xml舉例。
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="CHILDREN">
<title>Harry Potter</title>
<year>2005</year>
</book>
</bookstore>
如上第一行為xml文檔的說明,version和enconding分別代表當前xml文檔的版本和編碼方式。
xml元素:XML 元素指的是從(且包括)開始標簽直到(且包括)結束標簽的部分。一個元素可以包含:子元素、文本、屬性。
如bookstore元素為根元素、book元素為bookstore的子元素,category="CHILDREN"為book元素的屬性。title元素為book元素的子元素,Harry Potter為其文本。
二、項目配置:
pro文件里面添加QT+=xml,操作xml的頭文件包含include <QtXml>或include <QDomDocument>。
三、寫xml:
void HandleXml::writeXml(QString xmlPath) { QFile file(xmlPath); //相對路徑、絕對路徑、資源路徑都可以 if(!file.open(QFile::WriteOnly|QFile::Truncate)) //可以用QIODevice,Truncate表示清空原來的內容 return; QDomDocument doc; QDomProcessingInstruction instruction; //添加xml說明 instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\""); doc.appendChild(instruction); QDomElement root=doc.createElement("bookstore"); //創建根元素 doc.appendChild(root); //添加根元素 QDomElement bookElement=doc.createElement("book"); //一級子元素 bookElement.setAttribute("category","CHILDREN"); //方式一:創建屬性 其中鍵值對的值可以是各種類型 // QDomAttr category=doc.createAttribute("time"); //方式二:創建屬性 值必須是字符串 // category.setValue("CHILDREN"); // bookElement.setAttributeNode(time); QDomElement titleElement=doc.createElement("title"); //二級子元素 titleElement.appendChild(doc.createTextNode("Harry Potter")); //為titleElement元素增加文本 QDomElement yearElement=doc.createElement("year"); //二級子元素 yearElement.appendChild(doc.createTextNode("2005")); //為yearElement元素增加文本 bookElement.appendChild(titleElement); //增加子元素 bookElement.appendChild(yearElement); root.appendChild(bookElement); QTextStream out_stream(&file); //輸出到文件 doc.save(out_stream,2); //縮進4格 file.close(); }
四、讀xml:
void HandleXml::readXml(QString xmlPath) { QFile file(xmlPath); if(!file.open(QFile::ReadOnly)) return; QDomDocument doc; if(!doc.setContent(&file)) { file.close(); return; } file.close(); QDomElement bookStoreElement=doc.documentElement(); //返回根元素 qDebug()<<"開始打印xml內容:"; qDebug()<<bookStoreElement.tagName(); QDomNodeList bookNodeList=bookStoreElement.childNodes(); for(int i=0; i<bookNodeList.count(); i++) { QDomElement bookElement=bookNodeList.at(i).toElement(); qDebug()<<" "<<bookElement.tagName()<<" "<<bookElement.attribute("category",""); QDomNodeList childNodeList=bookElement.childNodes(); for(int j=0; j<childNodeList.count(); j++) { QDomElement childElement=childNodeList.at(i).toElement(); qDebug()<<" "<<childElement.tagName()<<" "<<childElement.text(); } } }
打印如下:
"bookstore"
"book" "CHILDREN"
"title" "Harry Potter"
"title" "Harry Potter"