Qt中讀寫xml檔案
阿新 • • 發佈:2019-02-16
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("title"), 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("title"), 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; }
參考資料