PDA

View Full Version : Replacing XML element value using QDomDocument



mj
14th March 2012, 14:04
Hi,
Im using QDomDocument for xml file.

My xml file has the following data,



<?xml version="1.0"?>
<config>
<dbus>
<gas_value>2</gas_value>
</dbus>
</config>



I want to replace <gas_value>2</gas_value> with <gas_value>100</gas_value>

Im using following code to replace it



QFile *file = new QFile("dbus_write.xml");

if (!file->open(QIODevice::ReadWrite | QIODevice::Text))
{
qDebug() << "unable to open xml file";
return;
}

QDomDocument doc("dbus_write");
doc.setContent(file);

QDomElement root = doc.firstChildElement("config");
QDomElement parent = root.firstChildElement("dbus");
QDomElement gasvalue = parent.firstChildElement("gas_value");
parent.firstChildElement("gas_value").firstChild().setNodeValue("100");
QTextStream stream(file);
gasvalue.save(stream, 4);
file->close();



but this code doesn't replaces the tag <gas_value>2</gas_value> , instead it creates another tag <gas_value>100</gas_value>
and produces following xml file



<?xml version="1.0"?>
<config>
<dbus>
<gas_value>2</gas_value>
</dbus>
</config>

<gas_value>100</gas_value>



I tried using replaceChild() method, but results in same output.

Any thoughts?
thanks.

mj
15th March 2012, 06:12
solved.. below code works fine for me..

QFile *file = new QFile("dbus_write.xml");

if (!file->open(QIODevice::ReadWrite | QIODevice::Text))
{
qDebug() << "unable to open xml file";
return;
}
QByteArray xmlData(file->readAll());
QDomDocument doc("dbus_write");
doc.setContent(xmlData);

QDomElement root = doc.firstChildElement("config");
QDomElement parent = root.firstChildElement("dbus");
QDomElement gasvalue = parent.firstChildElement("gas_value");
parent.firstChildElement("gas_value").firstChild().setNodeValue("100");
file->resize(0);
QTextStream stream(file);
stream.setDevice(file);
doc.save(stream, 4);
file->close();

ChrisW67
15th March 2012, 08:15
You should address the memory leak surrounding the (unnecessary) use of the heap for your QFile instance.