多层嵌套的xml 文件读取

#include <QXmlStreamReader>
#include <QFile>
#include <QDebug>

int main()
{
    QFile file("example.xml");
    if (!file.open(QFile::ReadOnly | QFile::Text)) {
        qDebug() << "Failed to open file.";
        return -1;
    }

    QXmlStreamReader reader(&file);

    while (!reader.atEnd() && !reader.hasError()) {
        QXmlStreamReader::TokenType token = reader.readNext();
        if (token == QXmlStreamReader::StartDocument) {
            continue;
        }

        if (token == QXmlStreamReader::StartElement) {
            qDebug() << reader.name().toString() << ":";
            QXmlStreamAttributes attributes = reader.attributes();
            for (int i = 0; i < attributes.size(); i++) {
                qDebug() << "  " << attributes[i].name().toString() << " = " << attributes[i].value().toString();
            }
        }

        if (token == QXmlStreamReader::EndElement) {
            qDebug() << "";
        }

        if (token == QXmlStreamReader::Characters) {
            QString text = reader.text().toString().trimmed();
            if (!text.isEmpty()) {
                qDebug() << "  " << text;
            }
        }
    }

    if (reader.hasError()) {
        qDebug() << "XML error: " << reader.errorString();
    }

    file.close();

    return 0;
}

 

posted @ 2023-09-13 17:01  SusieSnail_SUN  阅读(137)  评论(0编辑  收藏  举报