首先在.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(); // 移动到下一个节点或元素。
}