dom怎么修改xml节点文本值

2025-05-23 17:41:13
推荐回答(1个)
回答(1):

void setElementText(const QString &tagName,const QVariant &tagValue)
{
try
{
QFile file(configFile());
QDomDocument doc;
if (!doc.setContent(&file))
{
file.close();
return ;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomNodeList nodeList = docElem.elementsByTagName(tagName);
if (nodeList.count() >0 )
{
QDomElement el = nodeList.at(0).toElement();
QDomNode oldnode = el.firstChild();
el.firstChild().setNodeValue(tagValue.toString());
QDomNode newnode = el.firstChild();
el.replaceChild(newnode,oldnode);

if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
{
return ;
}
QTextStream out(&file);
doc.save(out,4);
file.close();
}
}
catch (...)
{
return ;
}
}