首页 > 技术文章 > QT读写xml配置文件

xupeidong 2019-01-29 10:36 原文

//获取字符串字段
QString ConfigHelper::GetStringConfigValue(QString str) {

    if(str == "InitDeviceNo")
    {
        return getMacPath();
    }else
    {
        QString filePath=QString("%1/%2").arg( qApp->applicationDirPath()).arg("config.xml");
        QString names=QString::null;
        ////打开或创建文件
        QFile file(filePath); //相对路径、绝对路径、资源路径都行
        if(!file.open(QFile::ReadOnly))
        {

        }
        QDomDocument doc;
        if(!doc.setContent(&file))
        {
            file.close();
        }
        file.close();
        QDomElement root=doc.documentElement(); //返回根节点
        QDomNode node=root.firstChild(); //获得第一个子节点
        while(!node.isNull())  //如果节点不空
        {
            if(node.isElement()) //如果节点是元素
            {

                QDomElement e=node.toElement(); //转换为元素,注意元素和节点是两个数据结构,其实差不多
                if(e.attribute("key")==str)
                {

                    names=e.attribute("value");
                   break;
                }

            }
            node=node.nextSibling(); //下一个兄弟节点,nextSiblingElement()是下一个兄弟元素,都差不多
        }
        return names;
    }
}

 

2、修改xml节点的值

    QString strPath = "l";
    QString name;
    QDomDocument doc;
    QFile file(strPath);
    if (!file.open(QIODevice::ReadOnly))
    {
        return;
    }
    if (!doc.setContent(&file))
    {
        file.close();
        return;
    }

    file.close();

    QDomElement rootElem = doc.documentElement();
    QDomNode rootNode = rootElem.firstChild();
    while(!rootNode.isNull())
    {
        qDebug() << rootNode.nodeName();
        QDomElement fileElem = rootNode.toElement();
        if(!fileElem.isNull())
        {
            name = fileElem.tagName();
            if(name == "CenterUrl")
            {
                QDomElement newnode = doc.createElement("CenterUrl");
                QDomText text = doc.createTextNode("10000");
                newnode.appendChild(text);
                rootElem.replaceChild(newnode,rootNode);
            }
        }
        rootNode = rootNode.nextSibling();
    }

    QString xml = doc.toString();

    if(!file.open(QFile::WriteOnly|QFile::Truncate))
    {
        return;
    }

    QTextStream out(&file);
    out<<xml;
    file.close();

 

这个读写XML的类我没怎么深研究过,毕竟是QT封装好的,用了这么多年了,大家有什么问题,评论区讨论下吧。

推荐阅读