使用QXmlStreamReader对xml文件的解析

前两天写了一个解析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。

这个函数的文档其实看过,但是没仔细看,所以浪费了好多时间。这次练习得到的经验是:以后看帮助文档一定要耐心看。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值