本文主要是介绍Qt 解析多级XML,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
补充笔记:Qt 史上最详细 - “操作XML文件” - 笔记
一、如下图为XML文件
annotation为根节点, first第一节点,second第二节点,third第三节点。
二、实现解析xml文件,并将解析数据用QTreeView显示,实现代码如下
① .h文件
class ParamSettingDlg : public QDialog
{Q_OBJECTpublic:explicit ParamSettingDlg(QWidget *parent = nullptr);~ParamSettingDlg();private:Ui::ParamSettingDlg *ui;QStandardItemModel *model;
};
② cpp文件
void ParamSettingDlg::LoadClassifyFile()
{QDomDocument doc;QString strXMLPath = QApplication::applicationDirPath() + + "/config/classify.xml";model = new QStandardItemModel(ui->treeView);model->setHorizontalHeaderLabels(QStringList()<<QStringLiteral("Classify"));QFile file(strXMLPath);if (!file.open(QIODevice::ReadOnly))return;QString strError;int iErrCount;int iErrLine;if ( !doc.setContent(&file, false, &strError, &iErrLine, &iErrCount) ){LoggerInfo::GetInstance()->WriteLog(LOG_LEVEL_ERROR,"Open XML Failed : " + strError ,__FUNCTION__,__LINE__);file.close();return ;}//! 根节点QDomElement root = doc.documentElement();//一级节点QDomElement firstNode = root.firstChildElement("first");for (; !firstNode.isNull(); firstNode = firstNode.nextSiblingElement("first")){QList<QStandardItem*> firstItems;QStandardItem* item1 = new QStandardItem(firstNode.attribute("name"));firstItems.append(item1);model->appendRow(firstItems);ui->comboBox->addItem(item1->text());//二级节点QDomElement secondNode = firstNode.firstChildElement("second");for (; !secondNode.isNull(); secondNode = secondNode.nextSiblingElement("second")){QList<QStandardItem*> secondItems;QStandardItem* item2 = new QStandardItem(secondNode.attribute("name"));secondItems.append(item2);item1->appendRow(secondItems);ui->comboBox->addItem(item2->text());//三级节点QDomElement thirdNode = secondNode.firstChildElement("third");for (; !thirdNode.isNull(); thirdNode = thirdNode.nextSiblingElement("third")){QList<QStandardItem*> thirdItems;QStandardItem* item3 = new QStandardItem(thirdNode.attribute("name"));thirdItems.append(item3);item2->appendRow(thirdItems);ui->comboBox->addItem(item3->text());}}}ui->treeView->setModel(model);
}
三、实现效果图
这篇关于Qt 解析多级XML的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!