背景
xml文件主要用于将项目中的一些参数变量,保存在电脑本地,方便下次工程运行的时读取上次的变量状态,在网络上很容易就可以搜索到对xml的基本使用教程,Qt也提供了相关接口,但我觉得这些接口很零散,调用起来麻烦。
故此,我用Qt提供的基本接口进行二次封装,对xml文件增删改查更加方便好用的几个接口。
软件环境
Qt creator.5.13
QT += xml
头文件
#include <QtXml>
#include <QDomDocument>
class Xmldemo
{
public:
Xmldemo();
public:
/*
* 函数功能:创建xml文件
* 参数:
* filepath 创建路径(相对路径、绝对路径、资源路径都可以)
* 返回值:成功返回 ture ,否则返回false
*/
bool CreateXmlFile(QString filepath);
/*
* 函数功能:加载xml文件路径名称
* 参数:路径名称
* 返回值:无
*/
void LoadPath(QString pat);
/*
* 函数功能:添加一个节点
* NodePath -- 节点路径,如:"node1.node2...newnodeName"(根节点不用写)
* NodeValue -- 节点文本值
* AttributeNameValue -- 节点属性,"属性名称.属性值",如:"Type.1"
* 返回值:无
*/
void AddNode(QString NodePath,QString NodeValue = QString(),QString AttributeNameValue = QString());
/*
* 函数功能:删除一个节点
* NodePath -- 节点路径,如:"node1.node2...newnodeName"(根节点不用写)
* 返回值:无
*/
void DeleteNode(QString NodePath);
/*
* 函数功能:改变一个节点文本
* NodePath -- 节点路径,如:"node1.node2...newnodeName"(根节点不用写)
* 返回值:返回节点文本,如节点不存在则返回空
*/
void ChangeNodeText(QString NodePath,QString NewText);
/*
* 函数功能:改变一个节点属性值
* NodePath -- 节点路径,如:"node1.node2...newnodeName"(根节点不用写)
* NewAttributeNameValue -- 改变后的属性,"需要改的属性名称.属性值",如"decs.NewValue"
* 返回值:无
*/
void ChangeNodeAttribute(QString NodePath,QString NewAttributeNameValue);
/*
* 函数功能:获取一个节点Text文本
* NodePath -- 节点路径,如:"node1.node2...newnodeName"(根节点不用写)
* 返回值:节点文本,如节点不存在则返回空
*/
QString GetNodeText(QString NodePath);
/*
* 函数功能:获取一个节点属性值
* NodePath -- 节点路径,如:"root.node1.node2...newnodeName"(根节点不用写)
* AttributeName -- 节点属性名称,"属性名称",如:"Type"
* 返回值:属性值
*/
QString GetAttributeValue(QString NodePath,QString AttributeName);
private:
QString Xmlpath;
};
增
函数实现代码如下:
void Xmldemo::AddNode(QString NodePath,QString NodeValue,QString AttributeNameValue)
{
int findIndex;
QStringList NodeNamePath = NodePath.split(".");
QFile file(Xmlpath); //相对路径、绝对路径、资源路径都可以
if(!file.open(QFile::ReadOnly))
return ;
QDomDocument doc;
QString ret;
//从字节数组数据解析XML文档,并将其设置为文档的内容。它试图根据XML规范的要求检测文档的编码
if(!doc.setContent(&file))
{
file.close();
return ;
}
file.close();
QDomElement root=doc.documentElement();
QDomElement fetherNode = root;
QDomElement childNode;
if(root.isNull())
return;
for (findIndex = 0;findIndex<NodeNamePath.count()-1;findIndex++) {
childNode = fetherNode.firstChildElement(NodeNamePath.at(findIndex));
if(!childNode.isNull())
fetherNode = childNode;
else{
childNode = doc.createElement(NodeNamePath.at(findIndex));
fetherNode.appendChild(childNode);
fetherNode = childNode;
}
}
if(fetherNode.isNull() || findIndex != NodeNamePath.count()-1)
return;
QDomElement NewNode = doc.createElement(NodeNamePath.last());
if(!NodeValue.isEmpty())
{
QDomText text