Edit Value of a QDomElement?

This will do what you want (the code you posted will stay as is):

// Get element in question
QDomElement root = doc.documentElement();
QDomElement nodeTag = root.firstChildElement("firstchild");

// create a new node with a QDomText child
QDomElement newNodeTag = doc.createElement(QString("firstchild")); 
QDomText newNodeText = doc.createTextNode(QString("New Text"));
newNodeTag.appendChild(newNodeText);

// replace existing node with new node
root.replaceChild(newNodeTag, nodeTag);

// Write changes to same file
xmlFile.resize(0);
QTextStream stream;
stream.setDevice(&xmlFile);
doc.save(stream, 4);

xmlFile.close();

... and you are all set. You could of course write to a different file as well. In this example I just truncated the existing file and overwrote it.


Just to update this with better and simpler solution (similar like Lol4t0 wrote) when you want to change the text inside the node. The text inside the 'firstchild' node actually becomes a text node, so what you want to do is:

...
QDomDocument doc;
doc.setContent(xmlData);
doc.firstChildElement("firstchild").firstChild().setNodeValue(‌​"new text");

notice the extra firstChild() call which will actually access the text node and enable you to change the value. This is much simpler and surely faster and less invasive than creating new node and replacing the whole node.

Tags:

C++

Qt

Qt4

Qtxml