Qt使用XML流

很简单,如下所示:

#include 
#include 
#include 
#include 
#include 

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

你可能感兴趣的:(qt5,qt)