QT 读写xml

一、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"

坚持成就伟大
原文地址:https://www.cnblogs.com/xian-yongchao/p/13799844.html