QT4.8读入xml文件

注意需要在工程文件中加入QT += xml

采用Dom的读取方法,QT5以后版本还有新的方法

头文件需要包含:

#include <QFile>
#include <QCoreApplication>
#include <QtXml>
#include <QMessageBox>

源文件内容

	QDomDocument handle;
    QFile file("./food.xml");
    if(!file.open(QIODevice::ReadOnly)){
        QMessageBox::warning(nullptr,QObject::tr("fail"),QObject::tr("open food.xml fail!"),QMessageBox::Ok);
        return;
    }
    if(!handle.setContent(&file)){
        file.close();
        return;
    }
    file.close();

    //QDomNode fistNode = doc.firstChild();
    //qDebug() << fistNode.nodeName() << fistNode.nodeValue();
    QDomElement docElem = handle.documentElement();
    QDomNode nNode = docElem.firstChild();
    while(!nNode.isNull()){
        if(nNode.isElement()){
            QDomElement element = nNode.toElement();
            qDebug() << element.tagName() << element.attribute("id");
            QDomNodeList list = element.childNodes();
            for(int i = 0; i < list.count(); i++) {
                QDomNode node = list.at(i);
                if(node.isElement()){
                    qDebug() << "===="  << node.toElement().tagName() << node.toElement().text();
                }
            }
            nNode = nNode.nextSibling();
        }
    }

xml文件

<?xml version="1.0" encoding="utf-8"?>
<breakfast_menu>
  <food id="1">
    <name>Belgian Waffles</name>
    <price>5.95</price>
    <description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
    <calories>650</calories>
  </food>
  <food id="2">
    <name>Strawberry Belgian Waffles</name>
    <price>7.95</price>
    <description>Light Belgian waffles covered with strawberries and whipped cream</description>
    <calories>900</calories>
  </food>
</breakfast_menu>

打印输出

"food" "1" 
==== "name" "Belgian Waffles" 
==== "price" "5.95" 
==== "description" "Two of our famous Belgian Waffles with plenty of real maple syrup" 
==== "calories" "650" 
"food" "2" 
==== "name" "Strawberry Belgian Waffles" 
==== "price" "7.95" 
==== "description" "Light Belgian waffles covered with strawberries and whipped cream" 
==== "calories" "900"
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_小白鱼儿_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值