您的位置:首页 > 编程语言 > Qt开发

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

2017-12-13 01:03 162 查看
XML是一种类似于HTML的标记语言,提供了2种解析方法

DOM方法 ,读写

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的。自己跑一遍就有一个印象了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  qt dom