前两天写了一个解析xml文件的程序,这个xml文件很简单,程序也很简单,下面写下总结。
xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<fullName>
<firstName>Chen</firstName>
<lastName>Jia</lastName>
</fullName>
解析该xml文件的程序如下:
#include <QtCore/QCoreApplication>
#include <QtCore/QFile>
#include <QtCore/QXmlStreamReader>
#include <QtCore/QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QString firstName=NULL;
QString lastName=NULL;
QString filePath = "D:/Share/Qt/xmlreader/xmlreader/xmlreader.xml";
QFile xmlFile(filePath);
xmlFile.open(QIODevice::ReadOnly);
QXmlStreamReader xmlReader(xmlFile.readAll());
xmlReader.readNext();
qDebug()<<xmlReader.name();
while(!xmlReader.atEnd())
{
if(xmlReader.isStartElement())
{
if(xmlReader.name()=="firstName")
{
qDebug()<<xmlReader.name();
firstName+=xmlReader.readElementText();
}
if(xmlReader.name()=="lastName")
{
qDebug()<<xmlReader.name();
lastName+=xmlReader.readElementText();
}
if(xmlReader.name()=="fullName")
qDebug()<<xmlReader.name();
}
else if(xmlReader.isEndElement())
{
qDebug()<<QString("%1%2").arg("/").arg(xmlReader.name().toString());
xmlReader.readNext();
}
xmlReader.readNext();
}
qDebug()<<QString("%1 %2").arg(firstName).arg(lastName);
}
刚开始程序时无法解析xml文件的,后来经过更改,才成了上面这样。但是按照上面的程序,开始时我觉得应该可以解析出每个闭合的标签的,但是程序显示如下:
第一个双引号是xml中的第一行,后面只能解析出fullName的闭合标签,那firstName和lastName的闭合标签呢?开始百思不得其解,后来再次回头看Qt的帮助文档时才找到原因:
对于Qstring readElementText()函数,其说明如下:
Convenience function to be called in case a StartElement was read. Reads until the corresponding EndElement and returns all text in-between. In case of no error, the current token (see tokenType()) after having called this function is EndElement.
也就是说,readElementText()函数在解析出开始标签时,就可以解析元素的文本了,直到遇到结束标签。我的理解是,readElementText()函数中会有类似于readNext()这样的函数读取下一个元素并比较是否为endElement,所以当使用readElementText()读取完元素文本时,该元素的闭合标签已经被读走了,因此下面的解析中不能输出/firstName和/lastName。
这个函数的文档其实看过,但是没仔细看,所以浪费了好多时间。这次练习得到的经验是:以后看帮助文档一定要耐心看。