Qt create快速入门第三本 - 17.2 XML总结

  • XML是一种类似于HTML的标记语言,提供了2种解析方法
    1. DOM方法 ,读写
    2. SAX方法,读取
  • 使用前要在pro文件中添加QT+=xml
    标准的XML文档如下:
<? xml version = "1.0" encoding = "UTF-8"?>
<library>
    <book id = "01">
        <title>Qt</title>
        <author > shiming </author>
    </book>
    <book id = "02">
        <title>Linux</title>
        <author>yafei</author>
    </book>
</library>
  • 第一行成为XML说明或者成为XML序言,说明XML的版本号和XML的使用编码。(一定要按照格式,这里是区分大小写的,并且空格一定也不能少。不能会不识别)。
  • 第二行则是xml的根元素,因为第一个元素被称为根元素。(根据自己理解随意配对,想成成员也好,下属也好,都可以),对应QDomElement类。
  • 第三行则是library元素下的元素。(元素可以包含属性)其中book是元素名, id是属性名,01则是属性值,对应QDomAttr类。
  • 第四行包括了Qt这个文本内容,文本内容对应QDomText类

使用DOM创建和操作XML文档

  • 首先要添加头文件
#include <QtXml>
#include <QFile>
  • 添加代码
   QDomDocument doc;
    QDomProcessingInstruction instruction;
    instruction = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding="
                                                         "\"UTF-8\"");
    doc.appendChild(instruction);//添加xml说明
    //添加根元素
    QDomElement root = doc.createElement("书库");
    doc.appendChild(root);
    //添加第一个图书元素及其子元素
    QDomElement book = doc.createElement("图书");
    QDomAttr id = doc.createAttribute("编号");
    QDomElement title = doc.createElement("书名");
    QDomElement author = doc.createElement("作者");
    QDomText text;
    id.setValue(QString("1"));
    book.setAttributeNode(id);
    text = doc.createTextNode("Qt");
    title.appendChild(text);
    text = doc.createTextNode("shiming");
    author.appendChild(text);
    book.appendChild(title);
    book.appendChild(author);
    root.appendChild(book);
    //添加第二个图书元素及其子元素
    book = doc.createElement("图书");
    id = doc.createAttribute("编号");
    title = doc.createElement("书名");
    author = doc.createElement("作者");
    id.setValue(QString("2"));
    book.setAttributeNode(id);
    text = doc.createTextNode("Linux");
    title.appendChild(text);
    text = doc.createTextNode("yafei");
    author.appendChild(text);
    book.appendChild(title);
    book.appendChild(author);
    root.appendChild(book);
    QFile file("my.xml");
    if(! file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return ;
    QTextStream out(&file);
    //将文档保存到文件,4位子元素缩进字符数
    doc.save(out, 4);
    file.close();

这个其实也是很好理解的,就是一个树状结构,父子关系。想一下就ok的。自己跑一遍就有一个印象了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值