一: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;