补充笔记:Qt 史上最详细 - "操作XML文件" - 笔记
一、如下图为XML文件
annotation为根节点, first第一节点,second第二节点,third第三节点。
二、实现解析xml文件,并将解析数据用QTreeView显示,实现代码如下
① .h文件
cpp
class ParamSettingDlg : public QDialog
{
Q_OBJECT
public:
explicit ParamSettingDlg(QWidget *parent = nullptr);
~ParamSettingDlg();
private:
Ui::ParamSettingDlg *ui;
QStandardItemModel *model;
};
② cpp文件
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);
}