加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

XML 解析之QXmlStreamReader

发布时间:2020-12-15 23:14:59 所属栏目:百科 来源:网络整理
导读:xml: ?xml version="1.0" encoding="UTF-8"?librarybook id="01"titleQt/titleauthorshiming/author/bookbook id="02"titlelinux/titleauthorshiming/author/book/library 解析代码: QFile file(":/my.xml"); if(!file.open(QIODevice::ReadOnly)) { qDebu

xml:

<?xml version="1.0" encoding="UTF-8"?>
<library>
	<book id="01">
		<title>Qt</title>
		<author>shiming</author>
	</book>
	<book id="02">
		<title>linux</title>
		<author>shiming</author>
	</book>
</library>

解析代码:
QFile file(":/my.xml");
    if(!file.open(QIODevice::ReadOnly))
    {
        qDebug() << "Error: cannot open file";
        return 1;
    }

    QXmlStreamReader reader;

    //设置文件,这时会将流设置为初始状态
    reader.setDevice(&file);

    //如果没有读到文档结尾, 而且没有出现错误
    while(!reader.atEnd())
    {
        QXmlStreamReader::TokenType type = reader.readNext();

        //下面便根据几号的类型来进行不同的输出
        if(type == QXmlStreamReader::StartDocument)
        {
            qDebug() << reader.documentEncoding() << reader.documentVersion();
        }
        if(type == QXmlStreamReader::StartElement)
        {
            qDebug() << "<" << reader.name() << ">";
            if(reader.attributes().hasAttribute("id"))
            {
                qDebug() << reader.attributes().value("id");
            }
        }
        if(type == QXmlStreamReader::EndElement)
        {
            qDebug() << "</" << reader.name() << ">";
        }
        if(type == QXmlStreamReader::Characters && !reader.isWhitespace())
        {
            qDebug() << reader.text();
        }
    }

    //如果读取过程中出现错误,那么请输出错误信息
    if(reader.hasError())
    {
        qDebug() << "error" << reader.errorString();
    }
    file.close();
输出结果:

"UTF-8" "1.0"

< "library" >

< "book" >

"01"

< "title" >

"Qt"

</ "title" >

< "author" >

"shiming"

</ "author" >

</ "book" >

< "book" >

"02"

< "title" >

"linux"

</ "title" >

< "author" >

"shiming"

</ "author" >

</ "book" >

</ "library" >

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读