C++ 使用 QXmlStreamReader 读取 XML 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15328756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading an XML file using QXmlStreamReader
提问by Mouhamed Fakarovic
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 文件QXmlStreamReader
,但我真的不知道问题出在哪里。我的函数读取第一个标签的内容,但随后停止。
The form of the XML file:
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>
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;
}
}
}
回答by Mouhamed Fakarovic
The problem was in the form of the XML document. I needed to create a root tag.
问题出在 XML 文档的形式上。我需要创建一个根标签。
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>