基于Qt的xml简单的读写笔记

前端之家收集整理的这篇文章主要介绍了基于Qt的xml简单的读写笔记前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

以下是测试的xml:

<config>
   <path>XXXXXXXXXXX</path>
   <path1>XXXXXXXXXXX1</path1>
</config>


读写xml的代码

#include "xmlutil.h"

XmlUtil::XmlUtil()
{
}

void XmlUtil::writeXml(QString& path,QMap<QString,QString>& map){
    QFile file(path);
    if(not file.open(QIODevice::ReadWrite))
        return;
    QDomDocument doc;
    QDomElement rootEle = doc.createElement("config");
    doc.appendChild(rootEle);

    QMap<QString,QString>::const_iterator ite;
    for( ite=map.constBegin(); ite!=map.constEnd(); ite++){
        cout << ite.key().toStdString() <<"        " << ite.value().toStdString();
        QDomElement pathEle = doc.createElement(ite.key());
        pathEle.appendChild(doc.createTextNode(ite.value()));
        rootEle.appendChild(pathEle);
    }
    QTextStream out(&file);
    doc.save(out,QIODevice::ReadWrite);
    file.close();
}
QMap<QString,QString>* XmlUtil::readXml(QString& path){
    QMap<QString,QString>* map=new QMap<QString,QString>();
    QFile file(path);
    if(!file.open(QIODevice::ReadOnly)){
        return NULL;
    }
    QDomDocument doc;
    doc.setContent(&file);
    QDomElement rootEle = doc.documentElement();

    //把全部二级item存放在list中
    QDomNodeList secondItemlist = rootEle.childNodes();

    for(int i = 0;i < secondItemlist.count();i++) {
        QDomNode node    = secondItemlist.at(i);
        //          cout<<endl<<node.toElement().nodeName().toStdString()<<"000000000000"<<node.toElement().text().toStdString()<<"++++++++++++++++"<<endl;
        map->insert(node.toElement().nodeName(),node.toElement().text());

    }//end for

    file.close();
    return map;
}

测试:

QMap<QString,QString> map;
    map.insert("path","XXXXXXXXXXX");
    map.insert("path1","XXXXXXXXXXX1");
    XmlUtil xml;
    QString path=QString::fromStdString("config.xml");
    xml.writeXml(path,map);
    QMap<QString,QString>* ret=xml.readXml(path);

    QMap<QString,QString>::const_iterator ite;
    for( ite=ret->constBegin(); ite!=ret->constEnd(); ite++){
        cout << ite.key().toStdString() <<"        " << ite.value().toStdString();
    }

猜你在找的XML相关文章