c++qtqt4qtxml

Edit Value of a QDomElement?


I need to edit the text of a QDomElement - Eg

I have an XML file with its content as -

<root>    
    <firstchild>Edit text here</firstchild>
</root>

How do I edit the text of the child element <firstchild>?

I don't see any functions in the QDomElement of QDomDocument classes descriptions provided in Qt 4.7

Edit1 - I am adding more details.

I need to read, modify and save an xml file. To format of the file is as below -

<root>    
    <firstchild>Edit text here</firstchild>
</root>

The value of element needs to be edited.I code to read the xml file is -

QFile xmlFile(".\\iWantToEdit.xml");
xmlFile.open(QIODevice::ReadWrite);

QByteArray xmlData(xmlFile.readAll());

QDomDocument doc;
doc.setContent(xmlData);

// Read necessary values

// write back modified values?

Note: I have tried to cast a QDomElement to QDomNode and use the function setNodeValue(). It however is not applicable to QDomElement.

Any suggestions, code samples, links would we greatly welcome.


Solution

  • 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.