Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading an XML file using QXmlStreamReader

Tags:

c++

xml

qt

I want to read an XML file using QXmlStreamReader, but I really don't know where the problem is. My function reads the content of the first tag, but then it stops.

The form of the XML file:

 <?xml version="1.0" encoding="utf-8"?>
    <student>
        <firstName>mina</firstName> 
        <lastName>jina</lastName>
        <grade>13</grade>
    </student>
    <student>
        <firstName>Cina</firstName> 
        <lastName>fina</lastName>
        <grade>13</grade>
    </student>

The function:

void MainWindow::open() {
    QFile file(QFileDialog::getOpenFileName(this,"Open"));
    if(file.open(QIODevice::ReadOnly)) {
        QXmlStreamReader xmlReader;
        xmlReader.setDevice(&file);
        QList<Student> students;
        xmlReader.readNext();
        //Reading from the file
        while (!xmlReader.isEndDocument())
        {
            if (xmlReader.isStartElement())
            {
                QString name = xmlReader.name().toString();
                if (name == "firstName" || name == "lastName" ||
                        name == "grade")
                {
                    QMessageBox::information(this,name,xmlReader.readElementText());
                }
            }else if (xmlReader.isEndElement())
            {
                xmlReader.readNext();
            }
        }
        if (xmlReader.hasError())
        {
            std::cout << "XML error: " << xmlReader.errorString().data() << std::endl;
        }
    }
}
like image 343
Mouhamed Fakarovic Avatar asked Mar 10 '13 22:03

Mouhamed Fakarovic


People also ask

Which reader is used to read data from XML files?

The XmlTextReader class can be used to read XML documents. The read function of this document reads the document until the end of its nodes. In this article, I will show you how to use the XmlTextReader class to read an XML document and write data to the console. Since XML classes are defined in the System.

How do I read text in XML?

XML files are encoded in plaintext, so you can open them in any text editor and be able to clearly read it. Right-click the XML file and select "Open With." This will display a list of programs to open the file in. Select "Notepad" (Windows) or "TextEdit" (Mac).


1 Answers

The problem was in the form of the XML document. I needed to create a root tag.

The new form of the document is:

<?xml version="1.0" encoding="utf-8"?>
    <students>
        <student>
            <firstName>mina</firstName> 
            <lastName>jina</lastName>
            <grade>13</grade>
        </student>
        <student>
            <firstName>Cina</firstName> 
            <lastName>fina</lastName>
            <grade>13</grade>
        </student>
    </students>
like image 199
Mouhamed Fakarovic Avatar answered Sep 20 '22 21:09

Mouhamed Fakarovic