欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt工作笔记-对QXmlStreamWriter进一步的认识(写复杂的XML文件)

程序员文章站 2022-07-13 22:02:09
...

本程序已经极度精简了,

运行截图如下:

Qt工作笔记-对QXmlStreamWriter进一步的认识(写复杂的XML文件)

代码如下:

Qt工作笔记-对QXmlStreamWriter进一步的认识(写复杂的XML文件)
#include <QApplication>
#include <QXmlStreamWriter>
#include <QDebug>
#include <QFile>

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

    QFile file("my.xml");
    if (!file.open(QFile::ReadWrite|QIODevice::Truncate))
    {
        qDebug() << "Error: cannot open file";
        return 1;
    }


    QXmlStreamWriter stream(&file);
    stream.setAutoFormatting(true);
    stream.writeStartDocument();
    stream.writeStartElement("最外层");
    stream.writeTextElement("结点一", "哆啦A梦");
    stream.writeTextElement("结点二", "蜡笔小新");

    //第一个
    stream.writeStartElement("内一层");
    stream.writeTextElement("姓名", "球球");
    stream.writeTextElement("照片文件", "C:\\xxx.txt");
    stream.writeTextElement("家庭关系文件", "C:\\xxx.data");
    stream.writeTextElement("是否有宠物","有个鸡儿");
    stream.writeTextElement("月工资","13999");
    stream.writeTextElement("有几个男朋友","1");
    stream.writeStartElement("车有几个*");
    stream.writeAttribute("include", "1");
    stream.writeTextElement("前男友文件", "C:\\xxxx.xml");
    stream.writeEndElement();
    stream.writeEndElement();

    //第二个
    stream.writeStartElement("内一层");
    stream.writeTextElement("姓名", "球球");
    stream.writeTextElement("照片文件", "C:\\xxx.txt");
    stream.writeTextElement("家庭关系文件", "C:\\xxx.data");
    stream.writeTextElement("是否有宠物","有个鸡儿");
    stream.writeTextElement("月工资","13999");
    stream.writeTextElement("有几个男朋友","1");
    stream.writeStartElement("车有几个*");
    stream.writeAttribute("include", "1");
    stream.writeTextElement("前男友文件", "C:\\xxxx.xml");
    stream.writeEndElement();
    stream.writeEndElement();

    stream.writeEndDocument();
    file.close();

    qDebug() << "write finished!";

    return a.exec();
}