使用QXmlStreamReader读取XML文件 [英] Reading an XML file using QXmlStreamReader
本文介绍了使用QXmlStreamReader读取XML文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用 QXmlStreamReader
读取XML文件,但我真的不知道问题出在哪里.我的函数读取第一个标签的内容,但随后停止.
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.
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;
}
}
}
推荐答案
问题出在XML文档的形式.我需要创建一个根标签.
The problem was in the form of the XML document. I needed to create a root tag.
文档的新形式为:
<?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>
这篇关于使用QXmlStreamReader读取XML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文