Qt对xml文件的读写

一:Qt有封装好的库可以对xml进行读写操作,下面是作者搜集到的总结的比较优秀的一篇文章。

附上链接:https://blog.csdn.net/weixin_43519792/article/details/106366530

二:另外一种用的比较广泛的库是pugixml库,这个库是C++的xml处理库,本篇文章主要是针对这个库的一些用法总结。

1、优势:xml与qt自带的xml处理库有更加强大的运行速度,下面是对比图

可以看出优势还是很明显的。

2、pugixml库的官方下载下载地址

 

https://github.com/zeux/pugixml

解压后找到下面的三个文件,在Qt的项目目录下新建一个文件夹,将这三个文件添加到项目目录中

3、下面是代码示例

///读取XML文件

///添加头文件
#include "pugixml/pugiconfig.hpp"
#include "pugixml/pugixml.hpp"

///打开文件
QFile file(path);
if(!file.open(QFile::ReadOnly))
    return;

pugi::xml_document doc;
if(!doc.load_file(path.toStdString().c_str()))
        return ;
    
pugi::xml_node form = doc.root();
///获取根节点下的所有子节点
auto list = form.children();
for(auto nodeChild:list)
{
    ///判断节点类型
    if(node.type() != pugi::node_element)
        return ;
    ///输出节点名
    qDebug() << nodeChild.name();
    ///输出节点值,这里需要注意的是nodeChild.value()并不会输出节点的值
    qDebug() << nodeChild.child_value();
    ///获取节点的属性列表
    auto attrList = nodeChild.attributes();
    for(pugi::xml_attribute attr: attrList )
    {
        ///输出属性的名称和值
        qDebug() << attr.name();
        qDebug() << attr.value();    
    }
}
///获取下一个节点
pugi::xml nodeNext = node.next_sibling();
///获取上一个节点
pugi::xml nodeNext = node.previous_sibling()
///获取指定名的属性
pugi::xml_attribute attr = ndoe.attribute("name");


///写XML

//创建document对象
pugi::xml_document doc;
///创建xml描述
pugi::xml_node decl = doc.prepend_child(pugi::node_declaration);
decl.append_attribute("version") = "1.0";
decl.append_attribute("encoding") = "UTF-8";
//开始写xml数据
pugi::xml_node nodeRoot = doc.append_child("rooot");
nodeRoot .append_attribute("111") = "data1";
nodeRoot .append_attribute("222") = "data2";

pugi::xml_node nodeChild = nodeRoot .append_child("dataChild");
pugi::xml_node nodeChild1 = nodeChild .append_child("dataChild1");
pugi::xml_node nodeChild2 = nodeChild1 .append_child("dataChild2");

///也可以在添加属性
nodeRoot .append_attribute("Version") = "1.6";

///保存文件
if(!doc.save_file(savepath.toStdString().c_str()))
        qDebug() << "保存成功";
return;
     

 

 

 

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值