I want to update a single XML element in Qt v5.0.2.
Lets say this is my XML File:
<?xml version="1.0" encoding="utf-8"?>
<root>
<myValue1 value="1" />
<myValue2 value="2" />
</root>
I want to update the XML element myValue and set the value to 2.
<?xml version="1.0" encoding="utf-8"?>
<root>
<myValue1 value="2" />
<myValue2 value="2" />
</root>
How can I proceed in Qt with this issue? Certainly, I can create a QXmlStreamWriter
and write the complete XML(all 4 data lines), but I want to do something small and smart.
Use QDomDocument
:
QDomDocument doc;
doc.setContent(<your xml>);
QDomNodeList elems = doc.elementsByTagName("myValue1");
if (!elems.isEmpty())
{
QDomElement el = elems.at(0).toElement();
if (!el.isNull())
{
if (el.hasAttribute("value"))
{
el.setAttribute("value", "2");
}
}
}
qDebug() << doc.toString();