注意需要在工程文件中加入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"