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;
}
}
}
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.
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).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With