Qt简单读写xml

版权声明:未经博主允许,禁止转载 https://blog.csdn.net/Think88666/article/details/83476709

这里只简单举例,读写是关联在一起的。

xml文档的内容是:

<?xml version="1.0" encoding="UTF-8"?>
<fileinfo>
 <filename>test</filename>
 <filesize>1024MB</filesize>
</fileinfo>

首先在pro文件中加入

QT       += xml

所有代码

#include "widget.h"
#include <QApplication>
#include <QtXml>
#include <QFile>
#include <QDebug>

void writeXml(){
    QDomDocument doc;
    QFile file("test.xml");
    if(file.open(QIODevice::ReadWrite)){
        qDebug()<<"open successful!";
        QString header("version=\"1.0\" encoding=\"UTF-8\"");
        doc.appendChild(doc.createProcessingInstruction("xml",header));
        QDomElement tagFileInfo = doc.createElement("fileinfo");

        //QDomElement相当于加标签,QDomText相当于加内容<QDomElement>QDomText</QDomElement>
        QDomElement tagFileName = doc.createElement("filename");
        QDomText textFileName = doc.createTextNode("test");
        QDomElement tagFileSize = doc.createElement("filesize");
        QDomText textFileSize = doc.createTextNode("1024MB");

        tagFileName.appendChild(textFileName);
        tagFileSize.appendChild(textFileSize);
        tagFileInfo.appendChild(tagFileName);
        tagFileInfo.appendChild(tagFileSize);

        doc.appendChild(tagFileInfo);

        QTextStream stream(&file);

        stream<<doc.toString();
        qDebug()<<"write xml ok!!";

    }else{
        qDebug()<<"open file error!";
    }
}

void readXml(){
    QFile file("test.xml");
    if(file.open(QIODevice::ReadOnly)){
        qDebug()<<"open success";
        QDomDocument doc;
        doc.setContent(&file);
        //at(0)是<?xml version="1.0" encoding="UTF-8"?>,所以用at(1)
        QDomNodeList nodeList = doc.childNodes().at(1).childNodes();
        for(int i=0;i<nodeList.count();i++){
            QDomNode node = nodeList.at(i).firstChild();
            qDebug()<<nodeList.at(i).toElement().tagName()<<":"<<node.toText().data();
        }
    }
}

int main(int argc, char *argv[])
{
    writeXml();
    readXml();
}

猜你喜欢

转载自blog.csdn.net/Think88666/article/details/83476709
今日推荐