C++ 在 Qt 中解析 XML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3092387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:02:05  来源:igfitidea点击:

Parse a XML file in Qt

c++xmlqtxml-parsing

提问by stefan

Let's say I have an XML file like this:

假设我有一个这样的 XML 文件:

<?xml version="1.0" encoding="utf-8"?>
<name>
    <id>1</id>
</name>

How can I parse it and get the value of id?

我如何解析它并获得 的值id

std::string id = ...;

回答by Scrivener

Something like this will work:

像这样的事情会起作用:

xmlFile = new QFile("xmlFile.xml");
        if (!xmlFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
                QMessageBox::critical(this,"Load XML File Problem",
                "Couldn't open xmlfile.xml to load settings for download",
                QMessageBox::Ok);
                return;
        }
xmlReader = new QXmlStreamReader(xmlFile);


//Parse the XML until we reach end of it
while(!xmlReader->atEnd() && !xmlReader->hasError()) {
        // Read next element
        QXmlStreamReader::TokenType token = xmlReader->readNext();
        //If token is just StartDocument - go to next
        if(token == QXmlStreamReader::StartDocument) {
                continue;
        }
        //If token is StartElement - read it
        if(token == QXmlStreamReader::StartElement) {

                if(xmlReader->name() == "name") {
                        continue;
                }

                if(xmlReader->name() == "id") {
                    qDebug() << xmlReader->readElementText();
                }
        }
}

if(xmlReader->hasError()) {
        QMessageBox::critical(this,
        "xmlFile.xml Parse Error",xmlReader->errorString(),
        QMessageBox::Ok);
        return;
}

//close reader and flush file
xmlReader->clear();
xmlFile->close();

回答by sashoalm

I made a simplified version of @Scrivener's answer. Instead of reading from a file I just read from a QString variable and I removed the continue;blocks:

我制作了@Scrivener 答案的简化版本。我没有从文件中读取,而是从 QString 变量中读取,然后删除了continue;块:

QString xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
              "<name>\n"
              " <id>1</id>\n"
              "</name>\n";

QXmlStreamReader reader(xml);
while(!reader.atEnd() && !reader.hasError()) {
    if(reader.readNext() == QXmlStreamReader::StartElement && reader.name() == "id") {
        qDebug() << reader.readElementText();
    }
}