Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

c++ - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...