1 概述
Qt中解析XML文件有多种方法,参考资料[1]使用QXmlStreamReader类来读取并解析xml文件,而参考资料[2]则使用QDomDocument类来解析xml文件。
2 QDomDocument
参考资料[2][3][4]都给出了QDomDocument解析xml文件的方法,下面是一个用于测试的xml文件:
<?xml version="1.0" encoding="UTF-8"?> <datainformations> <dataspacing> <X>0.31341081081</X> <Y>0.31341081081</Y> <Z>0.08581081081</Z> </dataspacing> <dataorigin> <X>0.00000000000</X> <Y>0.00000000000</Y> <Z>0.00000000000</Z> </dataorigin> </datainformations>下面编写一个函数,用于解析上面的内容:
void parseXML(const QString &fname) { if(fname.isEmpty()) return; QFile file(fname); if(!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::information(nullptr,QString("title"),QString("open error!")); return; } QDomDocument domDocument; QString error; int row = 0,column = 0; if(!domDocument.setContent(&file,false,&error,&row,&column)) { QMessageBox::information(nullptr,QString("Error"),QString("parse file Failed at line row and column") + QString::number(row,10) + QString(",") + QString::number(column,10)); file.close(); return; } if(domDocument.isNull()) { QMessageBox::information(nullptr,QString("document is null!")); file.close(); return; } const QDomElement domElement = domDocument.documentElement(); const QString domElementTagName = domElement.tagName(); if (domElementTagName != DOMELEMENT_TAGNAME) { QMessageBox::information(nullptr,QString("Root Name is wrong!")); file.close(); return; } QVector3D dataspacing; QVector3D dataorigin; const QDomNodeList spacingOriginList = domElement.childNodes(); for(int i = 0; i < spacingOriginList.count(); ++i) { const QDomNode spacingNode = spacingOriginList.item(i); const QDomElement spacingElement = spacingNode.toElement(); const QString spacingTagName = spacingElement.tagName(); QVector3D *data = nullptr; if (spacingTagName == "dataspacing") { data = &dataspacing; } else if (spacingTagName == "dataorigin"){ data = &dataorigin; } if (!data) continue; const QDomNodeList xyzList = spacingElement.childNodes(); for(int j = 0; j < xyzList.count(); ++j) { const QDomNode xNode = xyzList.item(j); const QDomElement xElement = xNode.toElement(); const QString xTagName = xElement.tagName(); const QString xTagValue = xElement.text(); if (xTagName == "X") { data->setX(xTagValue.toDouble()); } else if (xTagName == "Y") { data->setY(xTagValue.toDouble()); } else if (xTagName == "Z") { data->setZ(xTagValue.toDouble()); } } } file.close(); qDebug() << "spacing:" << dataspacing; qDebug() << "origin:" << dataorigin; }
参考资料
[1]Qt XML读取写入操作