Qt resolve multi-level xml file

First, the following picture shows the XML file

  

 

   annotation as the root node, first node, second node, third third node.

Second, to achieve parsed xml file, and parses the data display QTreeView, codes are as follows

  ① .h file

class ParamSettingDlg : public QDialog
{
    Q_OBJECT

public:
    explicit ParamSettingDlg(QWidget *parent = nullptr);
    ~ParamSettingDlg();

private:
    Ui::ParamSettingDlg *ui;

    QStandardItemModel *model;
};

 

  ② cpp file

 

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);
}

Third, to achieve the effect of FIG.

  

 

Guess you like

Origin www.cnblogs.com/jiangson/p/11578427.html