Qt Xml的读、写、修改、删除

news2024/10/5 19:11:09

一、说明

Xml文件的创建、读取、修改、删除以下图格式为例。
在这里插入图片描述

二、导入xml

QT       += core gui xml

三、创建Xml

void MainWindow::Xml_Write(QString path)
{
    //! 打开或创建文件
    QFile file(path);
    if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return; //! Truncate表示清空原来的内容

    //!
    QDomDocument doc;

    //! 添加头文件
    //! <?xml version="1.0" encoding="UTF-8"?>
    QDomProcessingInstruction instruction = doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
    doc.appendChild(instruction);

    //! 添加根节点 <library> </library>
    QDomElement root=doc.createElement("library");
    doc.appendChild(root);
    //! 子节点一
    //! <book time="2021/12/21" id="1"></book>
    QDomElement book=doc.createElement("book");
    //! 将子节点添加到根节点
    root.appendChild(book);
    //! 设置子节点属性(2种方式)
    book.setAttribute("id",1);
    book.setAttribute("time","2021/12/21");

    //! 方式一
    //! book.setAttribute("id",1);
    //! book.setAttribute("time","2021/12/21");
    //! 方式二
    //! QDomAttr time=doc.createAttribute("time"); //方式二:创建属性 值必须是字符串
    //! time.setValue("2222/2/22");
    //! book.setAttributeNode(time);

    //! 子节点中 子元素一
    //! <title>C++ primer</title>
    QDomElement title = doc.createElement("title");
    book.appendChild(title);
    QDomText text = doc.createTextNode("C++ primer");
    title.appendChild(text);

    //! 子节点中 子元素二
    //! <author>Stanley Lippman</author>
    title = doc.createElement("author");
    book.appendChild(title);
    text=doc.createTextNode("Stanley Lippman");
    title.appendChild(text);

    //! 子节点二
    book=doc.createElement("book");
    //! 将子节点添加到根节点
    root.appendChild(book);
    //! 子节点二属性
    book.setAttribute("id",2);
    book.setAttribute("time","2022/2/22");

    //! 子节点二中 子元素一
    title=doc.createElement("title");
    book.appendChild(title);
    text=doc.createTextNode("Thinking in Java");
    title.appendChild(text);

    //! 子节点二中 子元素一
    title=doc.createElement("author");
    book.appendChild(title);
    text=doc.createTextNode("Bruce Eckel");
    title.appendChild(text);

    //! 子节点三
    book =doc.createElement("phone");
    //! 子节点添加到根节点
    root.appendChild(book);
    //! 子节点三属性
    book.setAttribute("id",3);
    book.setAttribute("xiaomi","11");

    //! 子节点三中 子元素一
    title = doc.createElement("price");
    book.appendChild(title);
    text = doc.createTextNode("999");
    title.appendChild(text);

    //! 子节点三中 子元素一
    title = doc.createElement("discount");
    book.appendChild(title);
    text = doc.createTextNode("998");
    title.appendChild(text);

    //输出到文件
    QTextStream out_stream(&file);
    doc.save(out_stream,4); //缩进4格
}

3.1 “写”说明

//! 1.

> //!   
> QDomDocument doc;

//! 2.添加头文件
//! <?xml version="1.0" encoding="UTF-8"?>

> QDomProcessingInstruction instruction =  doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\""); 
> doc.appendChild(instruction);

//! 3.添加根节点(根节点只能有一个,子节点和子节点的子节点个数不限)
//! <library> </library>

> QDomElement root = doc.createElement("library");
> doc.appendChild(root);

//! 4.节点root添加子节点 //! //! //!
QDomElement book=doc.createElement(“book”); //! 将子节点添加到根节点
root.appendChild(book);

//! 5.节点book添加节点元素(1)(以子节点Book)
//! <library>
//! ....<book id="1" time="2021/12/21"> </book>
//! </library>

> //! 方式一
> book.setAttribute("id",1); 
> book.setAttribute("time","2021/12/21");
> //! 方式二:创建元素对象 值必须是字符串 
> QDomAttr id=doc.createAttribute("id");
> id.setValue("1"); 
> book.setAttributeNode(id); 
> //! QDomAttr
> time=doc.createAttribute("time"); 
> time.setValue("2021/12/21");
> book.setAttributeNode(time);

//! 6.子节点book添加子节点
//!<library>
//! ....<book id="1" time="2021/12/21">
//! ........ <title></title>
//! ........ <author></author>
//! ....</book>
//! </library>

>   QDomElement title = doc.createElement("title"); 
>   book.appendChild(title); 
>   //!   
>   QDomElement author = doc.createElement("author");
>   book.appendChild(author);

//! 7.添加元素(2)
//! <library>
//! ....<book id="1" time="2021/12/21">
//! ........<title>C++ primer</title>
//! ........ <author>Stanley Lippman</author>
//! ....</book>
//! </library>

> //! 子节title点添加元素(2)
> //! 创建文本节点text,存储值 
> //! 将文本节点添加到子节点title 
> QDomText text = doc.createTextNode("C++ primer"); 
> title.appendChild(text);
> 
> //! 子节anthor点添加元素(2) 
> text=doc.createTextNode("Stanley Lippman");
> author.appendChild(text);
> //! 8. 保存 //! 打开或创建文件 QFile file(path);
> if(!file.open(QIODevice::WriteOnly | QIODevice::Truncate)) return; //!
> Truncate表示清空原来的内容 QTextStream out_stream(&file);
> doc.save(out_stream,4); //缩进4格

四、读

void MainWindow::Xml_Read(QString path)
{
    QFile file(path);
    if(!file.open(QFile::ReadOnly)) return;

    QDomDocument doc;
    bool Content = doc.setContent(&file);
    file.close();
    if(!Content) return;


    QDomElement root=doc.documentElement(); //返回根节点
    qDebug()<<root.nodeName();
    QDomNode node=root.firstChild(); //获得第一个子节点

    while(!node.isNull())  //如果节点不空
    {
        if(node.isElement()) //如果节点是元素
        {
            QDomElement e=node.toElement(); //转换为元素,注意元素和节点是两个数据结构,其实差不多
            //qDebug()<<e.nodeName()<<e.tagName()<<" "<<e.attribute("id")<<" "<<e.attribute("time"); //打印键值对,tagName和nodeName是一个东西
            //qDebug()<<e.firstChild().nodeName()<<e.firstChild().toElement().text();
            QDomNodeList list=e.childNodes();
            for(int i=0;i<list.count();i++) //遍历子元素,count和size都可以用,可用于标签数计数
            {
                QDomNode n=list.at(i);
                if(n.isElement()) qDebug()<<n.nodeName()<<":"<<n.toElement().text();
            }
        }
        node=node.nextSibling(); //下一个兄弟节点,nextSiblingElement()是下一个兄弟元素,都差不多
    }
}

4.1 “读”说明

//! 1.打开文件

QFile file(path);
if(!file.open(QFile::ReadOnly)) return;

QDomDocument doc;
bool Content = doc.setContent(&file);
file.close();
if(!Content) return;

//! 2.获取根节点

QDomElement root=doc.documentElement();
//! 打印根节点名
//! qDebug()<<root.nodeName(); // return "library";

//! 3.获取root的第一个子节点

QDomNode node=root.firstChild(); 

//! 4.获取root的下一个子节点

node=node.nextSibling();

//! 5.获取root的所有节点

QDomNodeList list=root.childNodes();

//! 6.各种属性 //! 是否是空节点,是空节点表示读完

node.isNull();

//! 是否是元素节点,即上述添加了元素的节点

node.isElement();

//! 读元素节点的元素(1) //! <book id="1" time="2021/12/21">
//! 为方便叙述,此处不具体写获取节点代码,此处node 表示book节点,后续node对应描述的节点,不再做说明

QDomElement e = node.toElement();
qDebug()<<e.nodeName();  		// return "book";
qDebug()<<e.tagName();   		// return "book";
qDebug()<<e.attribute("id"); 	// return "1";
qDebug()<<e.attribute("time"); 	// return "2021/12/21";

//! 读元素节点的元素(1)
//! <book id="1" time="2021/12/21">
//! …<title>C++ primer</title>
//! …<author>Stanley Lippman</author>
//! </book>
//! node 表示book节点

QDomElement e = node.toElement();
QDomNodeList list=e.childNodes();
QDomNode n=list.at(0);
if(n.isElement()) qDebug()<<n.nodeName()<<":"<<n.toElement().text(); // return "title : C++ primer";
n=list.at(1);
if(n.isElement()) qDebug()<<n.nodeName()<<":"<<n.toElement().text(); // return "author : Stanley Lippman";

五、添加子节点

void MainWindow::Xml_Add(QString path)
{
    //打开文件
    QFile file(path); //相对路径、绝对路径、资源路径都可以
    if(!file.open(QFile::ReadOnly))
        return;

    //增加一个一级子节点以及元素
    QDomDocument doc;
    bool Content = doc.setContent(&file);
    file.close();
    if(!Content) return;

    QDomElement root=doc.documentElement();
    QDomNode node=root.firstChild(); //获得第一个子节点
    int number = 0;
    while(!node.isNull())  //如果节点不空
    {
        number++;
        node= node.nextSibling();
    }
    qDebug()<<number;
    QDomElement book=doc.createElement("book");
    book.setAttribute("id",number+1);
    book.setAttribute("time","1813/1/27");

    QDomElement title=doc.createElement("title");
    QDomText 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)) return;//先读进来,再重写,如果不用truncate就是在后面追加内容,就无效了

    //输出到文件
    QTextStream out_stream(&file);
    doc.save(out_stream,4); //缩进4格
    file.close();
}

六、删除节点

void MainWindow::Xml_Delete(QString path)
{
    QFile file(path); //相对路径、绝对路径、资源路径都可以
    if(!file.open(QFile::ReadOnly)) return;

    //删除一个一级子节点及其元素,外层节点删除内层节点于此相同
    QDomDocument doc;
    bool Content = doc.setContent(&file);
    file.close();
    if(!Content) return;

    //! 根节点元素
    QDomElement root=doc.documentElement();
    //! 根据子节点标签名获取所有子节点
    QDomNodeList list=doc.elementsByTagName("book"); //由标签名定位
    for(int i=0;i<list.count();i++)
    {
        QDomElement e=list.at(i).toElement();
        if(e.attribute("time")=="2007/5/25")  root.removeChild(list.at(i)); //以属性名定位,类似于hash的方式,warning:这里仅仅删除一个节点,其实可以加个break
    }

    if(!file.open(QFile::WriteOnly|QFile::Truncate)) return;
    //输出到文件
    QTextStream out_stream(&file);
    doc.save(out_stream,4); //缩进4格
    file.close();
}

七、总结

有点忙,后面两个有时间在解释吧

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/661486.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【MySQL篇】Select语句原理详解

文章目录 MYSQL体系结构模块详解架构分层连接层服务层存储引擎 SQL的执行流程连接查询缓存语法解析和预处理词法解析语法分析预处理器 查询优化器执行计划存储引擎存储引擎基本介绍如何选择存储引擎&#xff1f; 执行引擎举例说明 对于一个开发工程师来说&#xff0c;了解一下 …

C语言读写ini配置文件

环境 windows 10 64bitClion 2023.1 ini简介 ini 文件格式是一种用于保存配置信息的简单文本格式。它通常由多个节(section)组成&#xff0c;每个节包含多个键值对(key-value pair)。 下面是 ini 文件的基本语法规则 一个ini文件由多个节组成&#xff0c;每个节用方括号([])括起…

《Java黑皮书基础篇第10版》 第17章【笔记】

第十七章 二进制I/O 17.1 引言 文件可以不严谨的分类为文本文件和二进制文件。文本文件指的是可以用文件编辑器进行查看和修改的&#xff0c;二进制文件则不可以使用文本编辑器查看和修改。 例如&#xff0c;Test.java文件储存在文本文件中&#xff0c;因此可以用文本编辑器…

MapReduce程序基本架构

MapReduce程序是以&#xff08;键/值&#xff09;对的形式来处理数据的&#xff0c;即可以通过以下的形式来表示&#xff1a; map: (K1,V1) ➞ list(K2,V2) reduce: (K2,list(V2)) ➞ list(K3,V3) 不令人惊奇的是&#xff0c;这是一种超越一般数据的数据流表示形式。在本文中…

使用PyMC进行时间序列分层建模

在统计建模领域&#xff0c;理解总体趋势的同时解释群体差异的一个强大方法是分层(或多层)建模。这种方法允许参数随组而变化&#xff0c;并捕获组内和组间的变化。在时间序列数据中&#xff0c;这些特定于组的参数可以表示不同组随时间的不同模式。 今天&#xff0c;我们将深…

ood的5C解题法(1)----管理类面试对象设计

管理类 概念 可以模拟/代替管理员日常工作的系统 下面用停车场系统做演示 答题流程 Clarify What&#xff1a;除题目中的名词外&#xff0c;从管理的名词考虑 parking lot是什么类型的&#xff1f;如果楼有多层&#xff0c;停车位也是多层&#xff0c;则parking lot->pa…

Windows Server 2019 OVF, updated Jun 2023 (sysin) - VMware 虚拟机模板

Windows Server 2019 OVF, updated Jun 2023 (sysin) - VMware 虚拟机模板 2023 年 6 月版本更新&#xff0c;现在自动运行 sysprep&#xff0c;支持 ESXi Host Client 部署 请访问原文链接&#xff1a;https://sysin.org/blog/windows-server-2019-ovf/&#xff0c;查看最新…

5、产品经理的工作职责OR主要工作技能和工具

1、产品经理的工作职责 我们通过一个案例来了解产品经理的工作职责。 老板让你给他点餐&#xff0c;你应该怎么做&#xff1f;你需要考虑哪一些方面的问题&#xff1f; 例如&#xff1a;你预算多少&#xff0c;预算是十块钱还是100块还是1000块。有没有忌口&#xff0c;口味…

【MYSQL篇】Update语句原理详解

文章目录 前言缓冲池Buffer PoolInnoDB 内存结构redo logundo logBinlog 总结 前言 前面的文章我们已经对MySQL的查询语句的执行流程进行了说明&#xff0c;感兴趣的可以去看看&#xff1a; 【MySQL篇】Select语句原理详解 本篇文章我们来聊聊 MySQL更新语句的执行原理。更新…

Win7系统提示Windows Defender无法扫描选定的文件解决方法

Win7 64位系统提示“Windows Defender无法扫描选定的文件”怎么办呢?使用Windows Defender扫描文件,结果弹出如下图窗口,该怎么解决呢,参考下文,一起来解决Win7系统提示“Windows Defender无法扫描选定的文件”的解决方法。 原因分析: 这是因为开启Defender扫描压…

java的序列化注解Serial、序列化版本号serialVersionUID

例如&#xff0c;jdk源码NTLMException类的定义&#xff0c;其中涉及到了序列化注解Serial和序列化版本号字段serialVersionUID&#xff1a; 序列化注解java.io.Serial&#xff1a; 序列化注解java.io.Serial是在javaSE-14版本引入的。通常注解实现了序列化类的序列化相关的函…

【JUC进阶】02. volatile关键字

目录 1、回顾JMM 1.1、可见性&#xff08;Visibility&#xff09; 1.2、原子性&#xff08;Atomicity&#xff09; 1.3、有序性&#xff08;Ordering&#xff09; 2、volatile 2.1、保证可见性 2.2、不保证原子性 2.3、防止指令重排 2.4、什么时候使用volatile 3、小…

微服务中「组件」集成

有品&#xff1a;There is no silver bullet&#xff1b; 一、简介 在微服务工程的技术选型中&#xff0c;会涉及到很多组件的集成&#xff0c;最常用包括&#xff1a;缓存、消息队列、搜索、定时任务、存储等几个方面&#xff1b; 如果工程是单服务&#xff0c;对于集成组件…

有趣的数学 关于自然常数e

一、e的值 自然常数&#xff08;也称欧拉数&#xff09;e是数学中最重要的数字之一。 2.7182818284590452353602874713527...... 二、从复利理解e 设想你在一家银行有一个银行账户&#xff0c;该银行付给你一个慷慨的利息年利率12%,一年计一次复利&#xff0e;你将一笔初始存款…

测试(二)

1.软件测试的生命周期 需求分析→测试计划→ 测试设计→ 测试开发→ 测试执行→ 测试评估 2.如何描述一个Bug 3.Bug的优先级 1、Blocker&#xff08;崩溃&#xff09;&#xff1a; 阻碍开发或测试工作的问题&#xff1b;造成系统崩溃、死机、死循环&#xff0c;导致数据库数…

Windows Server 2016 OVF, updated Jun 2023 (sysin) - VMware 虚拟机模板

2023 年 6 月版本更新&#xff0c;现在自动运行 sysprep&#xff0c;支持 ESXi Host Client 部署 请访问原文链接&#xff1a;https://sysin.org/blog/windows-server-2016-ovf/&#xff0c;查看最新版。原创作品&#xff0c;转载请保留出处。 作者主页&#xff1a;sysin.org…

Kubernetes 纯理论 贼干篇

Kubernetes理论 docker 容器引擎 docker compose 单机编排工具 docker swarm Docker容器多机编排工具&#xff0c;实现Docker容器的集群管理调度的工具 k8s 容器多机编排工具&#xff0c;占据80%以上的市场份额 mesos marathon mesos:分布式资管管理框架&#xff0c;可以对…

2019年全国硕士研究生入学统一考试管理类专业学位联考写作试题

写作:第56&#xff5e;57小题&#xff0c;共65分。其中论证有效性分析30分&#xff0c;论说文35分。 56&#xff0e;论证有效性分析 分析下述论述中存在的缺陷和漏洞&#xff0c;选择若干要点&#xff0c;写一篇600字左右的文章&#xff0c;对论证的有效性进行分析和评论。(论…

Linux终端与进程的关系 ( 1 ) -【Linux通信架构系列】

系列文章目录 C技能系列 Linux通信架构系列 C高性能优化编程系列 深入理解软件架构设计系列 高级C并发线程编程 期待你的关注哦&#xff01;&#xff01;&#xff01; 现在的一切都是为将来的梦想编织翅膀&#xff0c;让梦想在现实中展翅高飞。 Now everything is for the…

案例:从定性原因分析上升到定量原因分析

在定量原因分析时&#xff0c;主要是有四种定量思考的方法&#xff1a; 1、数据的居中趋势与离散程度分析&#xff1a;均值、标准差 2、 80-20分析&#xff1a;在所有的构成成分中&#xff0c;哪个成分占比最大 3、数据的相关性分析&#xff1a;是否存在强相关 4、敏感性分…