Qt5之使用流来读取xml

http://www.qter.org/portal.php?mod=view&aid=62php

一、新建QT控制台应用,在.pro中添加linux

QT += core xml

二、xml文件:函数

<?xml version="1.0" encoding="UTF-8"?>
<书库>
    <图书 编号="1">
        <书名>Qt</书名>
        <做者>shiming</做者>
    </图书>
    <图书 编号="2">
        <书名>linux</书名>
        <做者>yafei</做者>
    </图书>
</书库>

 

三、代码spa

#include <QCoreApplication>
#include <QtXml>
#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QFile file("my.xml");//创建指向my.xml文件的QFile对象.
    if(!file.open(QFile::ReadOnly | QFile::Text)) //以文本方式,只读打开文件
    {
        qDebug() << "打开失败";
        return -1;
    }

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

    while(!reader.atEnd()){  //若是没有读到文档结尾,并且没有出现错误
        QXmlStreamReader::TokenType type = reader.readNext();  //读取下一个记号,它返回记号的类型
//流读取器就是在一个循环中经过使用readNext()来不断读取记号,这里能够对不一样的记号和不一样的内容进行不一样的处理,‘
//便可以在本函数中进行,也能够在其余函数或者其余类中进行。
        //根据记号的类型来进行不一样的输出
        if(type == QXmlStreamReader::StartDocument){   //type == 2
            qDebug() << reader.documentEncoding()
                     << reader.documentVersion();
        }

        if(type == QXmlStreamReader::StartElement){  //type == 4
            qDebug() << type << "<" << reader.name() << ">";
            if(reader.attributes().hasAttribute("编号")){
                qDebug() << reader.attributes().value("编号");
            }
        }

        if(type == QXmlStreamReader::Characters && !reader.isWhitespace()){
            qDebug() << reader.text();
        }

        if(type == QXmlStreamReader::EndElement){  //type == 5
            qDebug() << "";
        }
    }

    // 若是读取过程当中出现错误,那么输出错误信息
    if (reader.hasError()) {
            qDebug() << "error: " << reader.errorString();
    }

    file.close();


    return a.exec();
}

 

相关文章
相关标签/搜索