在有的项目中,有一些启动加载的配置是用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节点包的值
}
一个基础的生成和读取就差不多完成了,后续有新内容再记录