QT之XML的解析與生成


1、解析

    QFile file(ui->comboBox->currentText());
    //打開文件
    bool isOK = file.open(QIODevice::ReadOnly | QIODevice::Text);
    if(isOK){
        QXmlStreamReader reader(&file);
        while(!reader.atEnd())
        {
            //判斷是否是節點的開始
            if(reader.isStartElement())
            {
                QXmlStreamAttributes attributes = reader.attributes();
                // headList代表要解析的值的對象
                for(int i = 0; i < headList.size(); i++){
                    QString str = valueList.at(i);
                    QStringList strList = str.split(",");
                    if(reader.name() == headList.at(i)){
                        for(int j = 0; j < strList.size(); j++){
                            ui->textEdit_2->append(strList.at(j)+": " + attributes.value(strList.at(j)).toString());
                        }
                    }
                }
            }
            reader.readNext();
        }
    }
    else
    {
        qDebug()<<"Open file hello.xml failure";
    }
    file.close();                    

2、XML的生成

    //這里是以樹的結構來生成XML的,最多3層
    QDomElement element, root, cElement,sElement;
    QDomProcessingInstruction instruction;//寫入xml的頭部,添加處理命令
    instruction = doc.createProcessingInstruction( "xml", "version = \'1.0\' encoding=\'UTF-8\'" );//設置xml的版本號和字節的格式
    doc.appendChild(instruction);//添加介紹

    root = doc.createElement("XML");//設置根節點為COMMAND
    doc.appendChild(root);

    for(int i = 0; i < ui->treeWidget->topLevelItemCount(); i++){   // 獲取父節點個數
        element = doc.createElement( "OBJECT" );//添加根節點下面的元素OBJECT
        for(int count = 0; count < ui->treeWidget->columnCount(); count++){     // 獲取所在列的數據
            element.setAttribute("name", ui->treeWidget->topLevelItem(i)->text(count));
            root.appendChild(element);
        }
        for(int j=0; j < ui->treeWidget->topLevelItem(i)->childCount(); j++){
            cElement = doc.createElement("paramer");
            for(int count = 0; count < ui->treeWidget->columnCount(); count++){
                cElement.setAttribute("name", ui->treeWidget->topLevelItem(i)->child(j)->text(count));
                element.appendChild(cElement);
            }
            for(int k=0; k < ui->treeWidget->topLevelItem(i)->child(j)->childCount(); j++){
                sElement = doc.createElement("packet");
                for(int count = 0; count < ui->treeWidget->columnCount(); count++){
                    sElement.setAttribute("name", ui->treeWidget->topLevelItem(i)->child(j)->child(k)->text(count));
                    cElement.appendChild(sElement);
                }
            }
        }
    }
  QFile file(fileName);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)){
        qDebug() << file.errorString();
        return;
    }
    QTextStream out(&file);
    doc.save(out, 4);
  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM