QT学习之读取xml中信息

慈云数据 2024-05-09 技术支持 36 0

背景:

我们每次注册后会生成对应的启动文件,格式如下,启动码最后要在测试工具使用的进行一个验证,验证通过后模块才能使用。所以我希望每次的xml都放在一个文件夹里,等我选择文件夹后,能提取所有xml中的对应信息;

我的XML格式如下,我需要将里的Pid\AId\SId\ACode等都提取出来,放在表格了;

在这里插入图片描述

// 选择xml所在文件夹
void QtWidgetsApplication32::on_selecXmltDir_clicked(){
    m_dirXML = QFileDialog::getExistingDirectory(this, tr("打开XML所在文件夹"), "D:/", QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);
    ui.xmlDir->setText("xml文件夹:"+m_dirXML);
}
// 生成excel文件
void QtWidgetsApplication32::on_buildExcelFile_clicked() {
    QDir dir(m_dirXML);
    if (!dir.exists()) {
        qWarning() 
        outPutMsg(QtDebugMsg, "QtWidgetsApplication32::buildExcelFile invoke end. 打开 1.csv 失败!");
        return;
    }
    QTextStream stream(&fileCsv);
    stream 
        if (fileInfo.isFile()) {
           // outPutMsg(QtDebugMsg, "file:"+ fileInfo.absoluteFilePath());
            buildExcelFile(fileInfo.absoluteFilePath(), &stream);
        }
        else if (fileInfo.isDir()) {
            outPutMsg(QtDebugMsg, "dir:" + fileInfo.absoluteFilePath());
            // 目录不处理
        }
    }  
    fileCsv.close();
    ui.csvName-setText("csv文件名:"+csvName);
    QMessageBox::information(nullptr, "提示", "生成csv文件成功!");
}
// 生成Excel文件
void QtWidgetsApplication32::buildExcelFile(Qstring fileNames, QTextStream * pStream) {
    int iRow = 0;
    outPutMsg(QtDebugMsg, "QtWidgetsApplication32::buildExcelFile invoke begin." + fileNames);
    QFile file(fileNames); // 打开xml文件
    if (!file.open(QIODevice::ReadOnly | QFile::Text))
    {
        outPutMsg(QtDebugMsg, "QtWidgetsApplication32::buildExcelFile invoke end. 打开" + fileNames + "失败!");
        return;
    }
    QXmlStreamReader reader(&file);
    QByteArray strACCode;
    while (!reader.atEnd()) {
        QXmlStreamReader::TokenType nType = reader.readNext();
        if (nType == QXmlStreamReader::StartElement) {
            QString tagStr = reader.name().toString();
            qDebug() 
                QXmlStreamAttributes  Attributes = reader.attributes();
                if (Attributes.hasAttribute("PId")) {
                    // 有属性的是大标签
                    outPutMsg(QtDebugMsg, "PR_PId=" + Attributes.value("PR_PId").toString());
                }
                else { 
                    // 没有属性的是ElementText
                    QString text = reader.readElementText();
                    *pStream 
            }
            else if(QString::compare(tagStr, QStringLiteral("PR_OpTime")) == 0) {
                QString text = reader.readElementText();
                *pStream 
                QString text = reader.readElementText();
                *pStream 
            if (reader.isStartDocument()){
                qDebug() 
            }
        }
    }
    QString filename = QString::fromLatin1(strACCode);
    outPutMsg(QtDebugMsg, filename);
    file.close();
    outPutMsg(QtDebugMsg, "QtWidgetsApplication32::buildExcelFile invoke end.");
}
微信扫一扫加客服

微信扫一扫加客服

点击启动AI问答
Draggable Icon