Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse a XML file in Qt

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

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

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

std::string id = ...;
like image 632
stefan Avatar asked Jun 22 '10 10:06

stefan


1 Answers

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();
like image 105
Scrivener Avatar answered Oct 02 '22 06:10

Scrivener