QT开发之XML(Stream接口)

从Qt 4.3开始引用了两个新的类来读取和写入XML文档:QXmlStreamReader和QXmlStreamWriter.  这个比SAX框架更简单,操作也更加方便.一些操作事件类型和一去看帮助文档.

新建控制台应用 ,名称为myXmlStream .在myXmlStream.pro中添加  QT  +=xml 


main.cpp


#include <QtCore/QCoreApplication>
#include <QFile>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QDebug>

void WirteXml(char *filename)
{
    QFile file(filename);
    if (!file.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "Error: cannot open file";
        return ;
    }

    QXmlStreamWriter stream(&file);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();
    stream.writeStartElement("bookmark");
    stream.writeAttribute("href", "http://blog.csdn.net/qq_21792169");
    stream.writeTextElement("title", "Linux_Google");
    stream.writeEndElement();
    stream.writeEndDocument();

    file.close();

    qDebug() << "write finished!";

}

void ReadXml(char *filename)
{
    QFile file(filename);
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug()<<"Error: cannot open file";
        return ;
    }

    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();


}

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

    ReadXml("./my.xml");
    WirteXml("./my2.xml");
    return a.exec();
}



my2.xml

<?xml version="1.0" encoding="UTF-8"?>
<bookmark href="http://blog.csdn.net/qq_21792169">
    <title>Linux_Google</title>
</bookmark>



                                                                                                                                    文章出自:Linux_Google

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页