Qt使用XML流

很简单,如下所示:

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

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

    /*
    //读入
    QFile file("../myxmlstream/my.xml");//这个文件需要先创建好
    if (!file.open(QFile::ReadOnly | QFile::Text)){
        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();
*/

//写入
    QFile file("../myxmlstream/my2.xml");
    if (!file.open(QFile::WriteOnly | QFile::Text)){
        qDebug()<< "Error: cannot open file";
        return 1;
    }

    QXmlStreamWriter writer(&file);
    writer.setAutoFormatting(true); //会自动换行和缩进
    writer.writeStartDocument();    //会自动添加XML说明
    writer.writeStartElement("bookmark");
    writer.writeAttribute("href", "http://www.qt.io/");
    writer.writeTextElement("title", "Qt Home");
    writer.writeEndElement();
    writer.writeEndDocument();
    file.close();
    qDebug()<< "write finished";


    return a.exec();
}
    原文作者:ijiali
    原文地址: https://segmentfault.com/a/1190000020874482
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞