QT解析xml

首先在.pro工程文件中增加

QT += xml

例如读下面xml内容

<xml version="1.0" encoding="GB2312">
    <FL>
        <ITEM ID="1" MC="张三" />
        <ITEM ID="2" MC="李四" />
        <ITEM ID="3" MC="王五" />
    </FL>
</xml>

包含头文件

#include <QDomDocument>
#include <QFile>

解析实现如下:

        std::string sPath = "C:";
        QDomDocument xmlConfig;
        std::string sFilePath = sPath + "\\\\" + sFile;
        sFilePath += ".xml";

        QFile file(QString::fromStdString(sFilePath));
        if (!file.open(QIODevice::ReadOnly)) {
            std::cout << "QFile false"<< std::endl;
            return false;
        }

        QString errorStr;
        int errorLine, errorColumn;
        if (!xmlConfig.setContent(&file, &errorStr, &errorLine, &errorColumn)) {
            qDebug() << "Parse error at line" << errorLine << "," << errorColumn << ":" << errorStr;
            file.close();
            return false;
        }

        file.close();


        QDomElement docElemP = xmlConfig.documentElement(); // 获取根元素
        QDomElement docElemP2 = docElemP.firstChildElement("FL");
        QDomNode ITEM1 = docElemP2.firstChild(); // 遍历子节点或元素
        while(!ITEM1.isNull()) // 遍历所有节点或元素直到末尾
        {
            QDomElement eITEM1 = ITEM1.toElement(); // 将节点转换为元素以访问其属性或文本内容等。
            if(!eITEM1.isNull())
            {
                // 确保节点是元素节点,而不是其他类型的节点。
                //ID
                std::string strId = eITEM1.attribute("ID").toStdString();
                //NAME
                std::string strType = eITEM1.attribute("MC").toStdString();
                qDebug() << "InitFromFileXMFL:" + eITEM1.attribute("MC") << endl;
            }

            ITEM1 = ITEM1.nextSibling(); // 移动到下一个节点或元素。
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值