QXmlStreamReader/QXmlStreamWriter实现Qt下xml文件读写
本文标题:QXmlStreamReader/QXmlStreamWriter实现Qt下xml文件读写 本文地址:http://techieliang.com/2017/12/714/
1. 介绍
帮助文档:QXmlStreamReader、QXmlStreamWriter
除此以外读取时还需要使用QXmlStreamAttributes
1.1. QXml-Token标记类型
| Constant | Value | Description |
|---|---|---|
QXmlStreamReader::NoToken |
0 |
The reader has not yet read anything. |
QXmlStreamReader::Invalid |
1 |
An error has occurred, reported in error() and errorString(). |
QXmlStreamReader::StartDocument |
2 |
The reader reports the XML version number in documentVersion(), and the encoding as specified in the XML document in documentEncoding(). If the document is declared standalone, isStandaloneDocument() returns true; otherwise it returns false. |
QXmlStreamReader::EndDocument |
3 |
The reader reports the end of the document. |
QXmlStreamReader::StartElement |
4 |
The reader reports the start of an element with namespaceUri() and name(). Empty elements are also reported as StartElement, followed directly by EndElement. The convenience function readElementText() can be called to concatenate all content until the corresponding EndElement. Attributes are reported in attributes(), namespace declarations in namespaceDeclarations(). |
QXmlStreamReader::EndElement |
5 |
The reader reports the end of an element with namespaceUri() and name(). |
QXmlStreamReader::Characters |
6 |
The reader reports characters in text(). If the characters are all white-space, isWhitespace() returns true. If the characters stem from a CDATA section, isCDATA() returns true. |
QXmlStreamReader::Comment |
7 |
The reader reports a comment in text(). |
QXmlStreamReader::DTD |
8 |
The reader reports a DTD in text(), notation declarations in notationDeclarations(), and entity declarations in entityDeclarations(). Details of the DTD declaration are reported in in dtdName(), dtdPublicId(), and dtdSystemId(). |
QXmlStreamReader::EntityReference |
9 |
The reader reports an entity reference that could not be resolved. The name of the reference is reported in name(), the replacement text in text(). |
QXmlStreamReader::ProcessingInstruction |
10 |
The reader reports a processing instruction in processingInstructionTarget() and processingInstructionData(). |
主要是用StartDocument、EndDocument文档开始结束,StartElement、EndElement元素开始结束、Characters特征
1.2. 范例xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <bookmark href="http://qt-project.org/">
- <title>Qt Project</title>
- </bookmark>
第一行为StartDocument
bookmark、title为StartElement,/bookmark、/title为EndElement
href为attributes的一项,可以有多项,通过QXmlStreamAttributes::value获取后面的地址内容
Qt Project是title这个element的charcters
2. 写xml
- #include <QCoreApplication>
- #include <QFile>
- #include <QXmlStreamWriter>
- int main2(int argc, char *argv[]) {
- QCoreApplication a(argc, argv);
- QFile file("test.xml");
- if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
- QXmlStreamWriter stream(&file);
- stream.setAutoFormatting(true);
- stream.writeStartDocument();
- stream.writeStartElement("bookmark");
- stream.writeAttribute("href", "http://qt-project.org/");
- stream.writeTextElement("title", "Qt Project");
- stream.writeEndElement();
- stream.writeEndDocument();
- file.close();
- }
- return 0;
- }
写并不复杂,按顺序写即可,注意区分Attribute和Element,如果是一个小节用StartElement,如果是单行的类似于<title>Qt Project</title>可以直接用writeTextElement。
QXmlStreamWriter只是格式操作,并不提供文件操作,需要利用QFile建立文件并传递指针,也可以提供QString的指针,这样最终的xml信息会赋值到QString中。
3. 读xml
- #include <QCoreApplication>
- #include <QFile>
- #include <QXmlStreamReader>
- #include <QDebug>
- int main(int argc, char *argv[]) {
- QCoreApplication a(argc, argv);
- QFile file("test.xml");
- if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- QXmlStreamReader xml(&file);
- while (!xml.atEnd() && !xml.hasError()) {//循环逐行读取
- QXmlStreamReader::TokenType token = xml.readNext();
- if(token == QXmlStreamReader::StartDocument)//文件开始跳过
- continue;
- if(token == QXmlStreamReader::StartElement) {//StartElement类型,主要针对bookmark和title
- if(xml.name() == "bookmark") {//bookmark读取,其下attributes有但只有一个
- qDebug()<<"StartElement-"<<xml.name();
- QXmlStreamAttributes attributes = xml.attributes();
- if(attributes.hasAttribute("href")) {//针对href的attribute做判断
- qDebug()<<"Attributes-"<<attributes.value("href");//返回值是QStringRef
- }
- //多个attributes在这里增加更多的if
- continue;
- }
- if(xml.name() == "title") {//title
- xml.readNext();//没有attributes,理应直接进入while,此处偷懒了
- if(xml.isCharacters()) //可以做Characters判断也可以直接用text
- qDebug()<<"title-Characters-"<<xml.text();
- }
- }
- }
- if (xml.hasError()) {
- //范例,判断枚举类型,写出错误字符串
- if(xml.error() == QXmlStreamReader::CustomError) {
- //可以直接写出错误字符串
- qDebug()<<"error:" <<xml.errorString();
- }
- }
- }
- return 0;
- }
- 上述代码都没判断EndElement,不建议这样
- 建议进入每一个StartElement都直接开启一个while循环,直到循环到EndElement,从何保证对一个开头到结尾的完整操作,而不是像上述代码吧title放在和bookmark同级的循环内,并没有标明title包含于bookmark的关系,这样容易导致错误。
- 注意xml中每一个<>括住的项都作为一个标记,都占用一次readNext,其开头均为name,其后可能有attribute及对应value。
- 每两个<>XXX<>之间的XXX均作为一个Characters标记,也占用一次readNext,也就是上文中仍有未打印出的Character(“\n??? “换行符和四个空格、纯换行符):因为QXml以”\r”作为换行识别那么在前后两行的<><>之间还会余留一个\n;在title前的缩进也会当做一项Character。因此建议保证完整的包含关系并做好isXXX或者token枚举类型的判断以免被干扰。
3.1. 其他
除上述xml操作以外,Qt还提供了Qt XML模块,用于更高级的xml操作,提供了高速及使用便利的操作函数(不可兼得呀)
高速的SAX方法读取,QXmlSimpleReader及相关类
使用便捷的DOM方式:QDomDocument及相关类
使用这两个方法,由于是用的非core模块,需要在pro中添加qt += xml
QXmlStreamReader/QXmlStreamWriter实现Qt下xml文件读写的更多相关文章
- 实现动态的XML文件读写操作
实现动态的XML文件读写操作(依然带干货) 前言 最近由于项目需求,需要读写操作XML文件,并且存储的XML文件格式会随着导入的数据不同而随时改变(当然导入的数据还是有一定约束的),这样我们要预先定义 ...
- 实现动态的XML文件读写操作(依然带干货)
前言 最近由于项目需求,需要读写操作XML文件,并且存储的XML文件格式会随着导入的数据不同而随时改变(当然导入的数据还是有一定约束的),这样我们要预先定义好XML文件的格式就不太现实了,如何实现不管 ...
- Qt解析XML文件(QXmlStreamReader)
(2013-08-03 10:53:53) 转载▼ 如何使用QXmlStreamReader来解析格式良好的XML,Qt的文档中指出,它是一种更快.更方便的Qt自己的SAX解析器(QXml ...
- Qt对xml文件的读写
最近研究了一下qt下对xml文件的读写,小计一下,成为自己的知识. main函数调用: #include <QApplication> #include "readconfig. ...
- .NET下XML文件的读写
一.前言: XML是微软.Net战略的一个重要组成部分,而且它可谓是XML Web服务的基石,所以掌握.Net框架下的XML技术自然显得非常重要了.本文将指导大家如何运用C#语言完成.Net框架下的X ...
- 初识---Qt解析XML文件(QDomDocument)
关于XML及其使用场景不在此多做介绍,今天主要介绍Qt中对于XML的解析.QtXml模块提供了一个读写XML文件的流,解析方法包含DOM和SAX,两者的区别是什么呢? DOM(Document Ob ...
- 爪哇国新游记之十三----XML文件读写
/** * XML读写示例 * @author hx * */ public class XmlReaderWriter{ /** * 读取一个XML文件,返回一个雇员链表 * @param file ...
- [Unity基础]移动平台下的文件读写
From:http://blog.csdn.net/lyh916/article/details/52161633 参考链接: http://www.cnblogs.com/murongxiaopif ...
- Qt之xml文件解析
XML文件简介 XML - EXtensible Markup Language,可拓展标记语言 Qt中加载XML模块 .pro 文件中添加 QT += xml Qt的XML访问方式 引用:https ...
随机推荐
- 2.5 USB摄像头驱动程序框架
学习目标:根据vivi驱动架构和linux-2.6.31/linux-2.6.31.14/drivers/media/video/uvc/Uvc_driver.c驱动源码,分析usb摄像头驱动程序框架 ...
- Leecode刷题之旅-C语言/python-263丑数
/* * @lc app=leetcode.cn id=263 lang=c * * [263] 丑数 * * https://leetcode-cn.com/problems/ugly-number ...
- pgsql 变量赋值方法
1.网上一般说的方法如下: :=,赋值,比如user_id := 20; select into 赋值,比如 SELECT INTO myrec * FROM emp WHERE empname = ...
- (数据科学学习手札48)Scala中的函数式编程
一.简介 Scala作为一门函数式编程与面向对象完美结合的语言,函数式编程部分也有其独到之处,本文就将针对Scala中关于函数式编程的一些常用基本内容进行介绍: 二.在Scala中定义函数 2.1 定 ...
- eclipse安装hadoop插件
我想还有很多人没有听说过ZModem协议,更不知道有rz/sz这样方便的工具. 好东西不敢独享.以下给出我知道的一点皮毛. 下面一段是从SecureCRT的帮助中copy的: ZModem is a ...
- nth-child()伪类选择器
描述: 伪类:nth-child()的参数是an+b,如果按照w3.org上的描述,写成中文,很可能会让人头晕,再加上笔者的文笔水平有限,所以我决定避开an+b的说法,把它拆分成5种写法共5部分来说明 ...
- 【BZOJ3489】A simple rmq problem
[BZOJ3489]A simple rmq problem 题面 bzoj 题解 这个题不强制在线的话随便做啊... 考虑强制在线时怎么搞 预处理出一个位置上一个出现的相同数的位置\(pre\)与下 ...
- Jlink v8仿真器在64位系统上刷固件
1. 安装软件sam-ba_2.16.exe.本次主要是Jlink v8在64位系统下面的刷固件方法. 2. J-link通过USB连接至电脑,短接PCB上标号为ERASE的焊盘5秒,断开ERASE两 ...
- idea 新建 maven项目遇到的一些问题
idea创建好了maven项目之后,需要先在项目中添加 Web,这里创建Web时就会要求fix一个Artifacts,新建即可,然后面板设置默认即可(shift+ctrl+alt+s 打开面板): 然 ...
- Base64编码后通过Url传值
Base64编码简介 Base编码使用"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",再加上补 ...