我想使用QXmlStreamReader
读取XML文件,但我真的不知道问题出在哪里。我的函数读取第一个标记的内容,但随后停止。
XML文件的格式:
<?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>
功能:
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;
}
}
}
答案 0 :(得分:9)
问题出在XML文档的形式。我需要创建一个根标签。
该文件的新形式是:
<?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>