Qt5 对xml文件常用的操作(读写,增删改查)
转自:https://blog.csdn.net/hpu11/article/details/80227093
项目配置
pro文件里面添加QT+=xml
include <QtXml>,也可以include <QDomDocument>
项目文件:
.pro 文件
QT += core xml QT -= gui TARGET = xmltest
CONFIG += console
CONFIG -= app_bundle TEMPLATE = app SOURCES += main.cpp
主程序:
main.cpp
#include <QCoreApplication>
#include <QtXml> //也可以include <QDomDocument> //写xml
void WriteXml()
{
//打开或创建文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::WriteOnly|QFile::Truncate)) //可以用QIODevice,Truncate表示清空原来的内容
return; QDomDocument doc;
//写入xml头部
QDomProcessingInstruction instruction; //添加处理命令
instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
doc.appendChild(instruction);
//添加根节点
QDomElement root=doc.createElement("library");
doc.appendChild(root);
//添加第一个子节点及其子元素
QDomElement book=doc.createElement("book");
book.setAttribute("id",); //方式一:创建属性 其中键值对的值可以是各种类型
QDomAttr time=doc.createAttribute("time"); //方式二:创建属性 值必须是字符串
time.setValue("2013/6/13");
book.setAttributeNode(time);
QDomElement title=doc.createElement("title"); //创建子元素
QDomText text; //设置括号标签中间的值
text=doc.createTextNode("C++ primer");
book.appendChild(title);
title.appendChild(text);
QDomElement author=doc.createElement("author"); //创建子元素
text=doc.createTextNode("Stanley Lippman");
author.appendChild(text);
book.appendChild(author);
root.appendChild(book); //添加第二个子节点及其子元素,部分变量只需重新赋值
book=doc.createElement("book");
book.setAttribute("id",);
time=doc.createAttribute("time");
time.setValue("2007/5/25");
book.setAttributeNode(time);
title=doc.createElement("title");
text=doc.createTextNode("Thinking in Java");
book.appendChild(title);
title.appendChild(text);
author=doc.createElement("author");
text=doc.createTextNode("Bruce Eckel");
author.appendChild(text);
book.appendChild(author);
root.appendChild(book); //输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,); //缩进4格
file.close(); } //读xml
void ReadXml()
{
//打开或创建文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都行
if(!file.open(QFile::ReadOnly))
return; QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close(); QDomElement root=doc.documentElement(); //返回根节点
qDebug()<<root.nodeName();
QDomNode node=root.firstChild(); //获得第一个子节点
while(!node.isNull()) //如果节点不空
{
if(node.isElement()) //如果节点是元素
{
QDomElement e=node.toElement(); //转换为元素,注意元素和节点是两个数据结构,其实差不多
qDebug()<<e.tagName()<<" "<<e.attribute("id")<<" "<<e.attribute("time"); //打印键值对,tagName和nodeName是一个东西
QDomNodeList list=e.childNodes();
for(int i=;i<list.count();i++) //遍历子元素,count和size都可以用,可用于标签数计数
{
QDomNode n=list.at(i);
if(node.isElement())
qDebug()<<n.nodeName()<<":"<<n.toElement().text();
}
}
node=node.nextSibling(); //下一个兄弟节点,nextSiblingElement()是下一个兄弟元素,都差不多
} } //增加xml内容
void AddXml()
{
//打开文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::ReadOnly))
return; //增加一个一级子节点以及元素
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close(); QDomElement root=doc.documentElement();
QDomElement book=doc.createElement("book");
book.setAttribute("id",);
book.setAttribute("time","1813/1/27");
QDomElement title=doc.createElement("title");
QDomText text;
text=doc.createTextNode("Pride and Prejudice");
title.appendChild(text);
book.appendChild(title);
QDomElement author=doc.createElement("author");
text=doc.createTextNode("Jane Austen");
author.appendChild(text);
book.appendChild(author);
root.appendChild(book); if(!file.open(QFile::WriteOnly|QFile::Truncate)) //先读进来,再重写,如果不用truncate就是在后面追加内容,就无效了
return;
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,); //缩进4格
file.close();
} //删减xml内容
void RemoveXml()
{
//打开文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::ReadOnly))
return; //删除一个一级子节点及其元素,外层节点删除内层节点于此相同
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close(); //一定要记得关掉啊,不然无法完成操作 QDomElement root=doc.documentElement();
QDomNodeList list=doc.elementsByTagName("book"); //由标签名定位
for(int i=;i<list.count();i++)
{
QDomElement e=list.at(i).toElement();
if(e.attribute("time")=="2007/5/25") //以属性名定位,类似于hash的方式,warning:这里仅仅删除一个节点,其实可以加个break
root.removeChild(list.at(i));
} if(!file.open(QFile::WriteOnly|QFile::Truncate))
return;
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,); //缩进4格
file.close();
} //更新xml内容
void UpdateXml()
{
//打开文件
QFile file("test.xml"); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::ReadOnly))
return; //更新一个标签项,如果知道xml的结构,直接定位到那个标签上定点更新
//或者用遍历的方法去匹配tagname或者attribut,value来更新
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
return;
}
file.close(); QDomElement root=doc.documentElement();
QDomNodeList list=root.elementsByTagName("book");
QDomNode node=list.at(list.size()-).firstChild(); //定位到第三个一级子节点的子元素
QDomNode oldnode=node.firstChild(); //标签之间的内容作为节点的子节点出现,当前是Pride and Projudice
node.firstChild().setNodeValue("Emma");
QDomNode newnode=node.firstChild();
node.replaceChild(newnode,oldnode); if(!file.open(QFile::WriteOnly|QFile::Truncate))
return;
//输出到文件
QTextStream out_stream(&file);
doc.save(out_stream,); //缩进4格
file.close();
} int main(int argc, char *argv[])
{ qDebug()<<"write xml to file...";
WriteXml();
qDebug()<<"read xml to display...";
ReadXml();
qDebug()<<"add contents to xml...";
AddXml();
qDebug()<<"remove contents from xml...";
RemoveXml();
qDebug()<<"update contents to xml...";
UpdateXml();
return ; }
写xml
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book id="1" time="2013/6/13">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book id="2" time="2007/5/25">
<title>Thinking in Java</title>
<author>Bruce Eckel</author>
</book>
</library>
增加xml
<?xml version='1.0' encoding='UTF-8'?>
<library>
<book time="2013/6/13" id="">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book time="2007/5/25" id="">
<title>Thinking in Java</title>
<author>Bruce Eckel</author>
</book>
<book time="1813/1/27" id="">
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
</book>
</library>
删除xml
<?xml version='1.0' encoding='UTF-8'?>
<library>
<book time="2013/6/13" id="">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book time="2007/5/25" id="">
<title>Thinking in Java</title>
<author>Bruce Eckel</author>
</book>
<book time="1813/1/27" id="">
<title>Pride and Prejudice</title>
<author>Jane Austen</author>
</book>
</library>
更新xml
<?xml version='1.0' encoding='UTF-8'?>
<library>
<book id="" time="2013/6/13">
<title>C++ primer</title>
<author>Stanley Lippman</author>
</book>
<book id="" time="1813/1/27">
<title>Emma</title>
<author>Jane Austen</author>
</book>
</library>
Qt5 对xml文件常用的操作(读写,增删改查)的更多相关文章
- 对xml文件的sax解析(增删改查)之一
crud(增删改查): c:creat r:retrieve u:update d:delete 以下笔记来自于韩顺平老师的讲解. 现在是用java来操作. 第一步:新建java工程.file-new ...
- 对xml文件的sax解析(增删改查)之二
先上代码: package com.saxparsetest; //the filename of this file is :saxparse.java import javax.xml.parse ...
- 使用DOM进行xml文档的crud(增删改查)操作<操作详解>
很多朋友对DOM有感冒,这里我花了一些时间写了一个小小的教程,这个能看懂,会操作了,我相信基于DOM的其它API(如JDOM,DOM4J等)一般不会有什么问题. 后附java代码,也可以下载(可点击这 ...
- js操作indexedDB增删改查示例
js操作indexedDB增删改查示例 if ('indexedDB' in window) { // 如果数据库不存在则创建,如果存在但是version更大,会自动升级不会复制原来的版本 var r ...
- MySQL数据分析(16)— 数据操作之增删改查
前面我们说学习MySQL要从三个层面,四大逻辑来学,三个层面就是库层面,表层面和数据层面对吧,数据库里放数据表,表里放数据是吧,大家可以回忆PPT中jacky的这图,我们已经学完了库层面和表层面,从本 ...
- Redis简单的数据操作(增删改查)
#Redis简单的数据操作(增删改查): 字符串类型 string 1. 存储: set key value 127.0.0.1:6379> set username zhangsan OK 2 ...
- 02 . Mysql基础操作及增删改查
SQL简介 SQL(Structured Query Language 即结构化查询语言) SQL语言主要用于存取数据.查询数据.更新数据和管理关系数据库系统,SQL语言由IBM开发. SQL语句四大 ...
- Django-Model操作数据库(增删改查、连表结构)
一.数据库操作 1.创建model表 基本结构 1 2 3 4 5 6 from django.db import models class userinfo(models.M ...
- 【DRP】-Dao层常用功能代码:增删改查
本系列博客内容为:做DRP系统中Dao层常用功能. 该项目采用MVC架构 C(Controller)控制器,主要职责;1.取得表单参数:2.调用业务逻辑:3.转向页面 M(Model)模型,主要职责: ...
随机推荐
- Python (2) 除法
/ 除法 自动转化为浮动数 // 整除 只保留整数部分 >>> 2/21.0>>> 2//21>>> 1 ...
- 初学oracle第三天
体系结构 Oracle 采取的是 Client/Server 架构. 3.1 Client 3.1.1 Sqlplus 这是一个轻量级的功能强大的客户端, 是 dba 必须掌握的工具. 我们可以配 ...
- [window] 使用Pyhton轻便好用的spyder IDE进行代码分析时如何指定相关的配置文件
spyder 使用pylint这个第三方库进行代码检查,其实pylint使用的代码规范默认也是pep8,不过该库还有 其它用途,在这里我专门写写在代码分析时,如何指定配置文件 一般来说,使用spyde ...
- #452 Div2 Problem C Dividing the numbers ( 思维 || 构造 )
题意 : 将从 1 ~ n 的数分成两组,要求两组和的差值尽可能小,并输出其中一组的具体选数情况 分析 : 如果将这 n 个数从大到小四个一组来进行选择的话那么差值就为 0 ,然后再来考虑 n%4 ! ...
- SQL 查询表字段长度, 名称, 类型, 存储过程创建和修改时间
获取存储过程的修改时间和创建时间查询建立时间 --表 select * from sysobjects where id=object_id(N'表名') and xtype='U' --表的结构 s ...
- 一些性能优化的tips
工作中积累的一些性能优化的tips,记录一下: 1. Message的创建 Message message = Message.obtain(); // 推荐 Message message = n ...
- Oracle-SQL程序优化案例二
有时候写得不规范的SQL语句真的是占用很多时间 以下是我在工作中发现的规律,如果字段过多的使用函数,尽量不要将这些字段串联在一起做匹配或查询条件,比如红色注释部分,在执行红色部分的时候 这个SQL程序 ...
- React Native商城项目实战12 - 首页头部内容
1.HomeTopView为首页头部内容,HomeTopListView为HomeTopView子视图. 2.HomeTopView.js /** * 首页头部内容 */ import React, ...
- UART协议详解
UART(Universal Asynchronous Receiver/Transmitter)是一种异步全双工串行通信协议,由Tx和Rx两根数据线组成,因为没有参考时钟信号,所以通信的双方必须约定 ...
- mongoexport导出记录到csv文件
root@service:~# mongoexport -d prod -c employees -f _id,platform,phone --csv -o /opt/employees.csv 2 ...