QT读取xml配置文件

时间:2023-03-09 01:06:29
QT读取xml配置文件
//获取字符串字段
QString ConfigHelper::GetStringConfigValue(QString str) { if(str == "InitDeviceNo")
{
return getMacPath();
}else
{
QString filePath=QString("%1/%2").arg( qApp->applicationDirPath()).arg("config.xml");
QString names=QString::null;
////打开或创建文件
QFile file(filePath); //相对路径、绝对路径、资源路径都行
if(!file.open(QFile::ReadOnly))
{ }
QDomDocument doc;
if(!doc.setContent(&file))
{
file.close();
}
file.close();
QDomElement root=doc.documentElement(); //返回根节点
QDomNode node=root.firstChild(); //获得第一个子节点
while(!node.isNull()) //如果节点不空
{
if(node.isElement()) //如果节点是元素
{ QDomElement e=node.toElement(); //转换为元素,注意元素和节点是两个数据结构,其实差不多
if(e.attribute("key")==str)
{ names=e.attribute("value");
break;
} }
node=node.nextSibling(); //下一个兄弟节点,nextSiblingElement()是下一个兄弟元素,都差不多
}
return names;
}
}