c++ - 在 Qt 中解析 XML 文件

标签 c++ xml qt xml-parsing

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

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

如何解析它并获取 id 的值?

std::string id = ...;

最佳答案

像这样的东西会起作用:

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

关于c++ - 在 Qt 中解析 XML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3092387/

相关文章:

c++ - 找不到 opencv naclport 构建输出

c# - 您知道从 XSD 创建 C++ 或 C# 类(数据模型)的优秀免费软件吗?

c++ - 我怎样才能返回一个数组?

c++ - 发送特定字节模式时串口数据损坏

xml - 类型映射 apachesoap 未解析

qt - 在 .pro 文件中强制使用特定版本的 QT

java - 如何在 XML 解析器抛出 MalformedByteSequenceException 后定位错误

Android - LinearLayout 中的中心 TextView

Qt:Q_PROPERTY 带有指针和用于 QtScript 访问的前向声明

c++ - 如何调用 Qt Quick 2 Extension Plugin 的方法?