QDomDocument使用经验

在有的项目中,有一些启动加载的配置是用xml格式的文件设置的,对于该类文件的读取可以用到QDomDocument这个类,同理有一些想要保留到本地的,方便下一次读取继续使用的配置也可以用该类生成并修改;
这里记录一下使用经验。

下面是一段使用QDomDocument生成一个xml文件的代码

QFile file(path);//path为我们需要输出的文件地址
bool ret = file.open(QIODevice::WriteOnly | QIODevice::Truncate);
//判断文件是否可写,Truncate意思是写入文件时会清空文件
if (!ret)
{
    return;
}

QDomDocument doc;
QDomProcessingInstruction instruction = doc.createProcessingInstruction(
    "xml", "version=\"1.0\"  encoding=\"UTF-8\"");
doc.appendChild(instruction);//设置预解析指令

QDomElement rootNode = doc.createElement("Section");
doc.appendChild(rootNode);//创建一个根节点,节点<Section></Section>

QDomElement menuGroupNode = doc.createElement("Group");
menuGroupNode.setAttribute("Name", "App");
rootNode.appendChild(menuGroupNode);
//创建一个根节点下的子节点,同时有一个属性值<Section><Group Name="App"></Group></Section>

QDomElement accChar = doc.createElement("Char");
menuGroupNode.appendChild(accChar);
QDomText accCharText = doc.createTextNode("aaa");
accChar.appendChild(accCharText);
//在Group节点下再添加一个子节点并且包一个值<Char>aaa</Char>
QTextStream out(&file);
doc.save(out, 4);
//保存该文件到本地path路径,缩进为4
file.close();

对于读取一个xml,也可以用该类

QFile xmlFile(path);
if (!xmlFile.open(QFile::ReadOnly))//判断打开path文件是否可读
{
    return false;
}
QDomDocument doc;
if (!doc.setContent(&xmlFile))//读xml文件是否成功
{
    xmlFile.close();
    return false;
}
xmlFile.close();

auto section = doc.elementsByTagName("Section").at(0);//查找Section下的所有元素
if (section.isNull())
{
    return false;
}
auto groupDom = section.firstChildElement(QString("Group"));//查找section下的子节点group
 for (QDomElement child = groupDom .firstChildElement(); !child.isNull();
     child = child.nextSiblingElement(QStringLiteral("Char")))
//nextSiblingElement指下一个兄弟元素,这样可以遍历Group节点下的子节点
{
	QString charStr = child.text();//得到Char节点包的值
}

一个基础的生成和读取就差不多完成了,后续有新内容再记录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值