问题描述
我需要编辑QDomElement的文本 - 例如
I need to edit the text of a QDomElement - Eg
我有一个XML文件,其内容为 -
I have an XML file with its content as -
<root>
<firstchild>Edit text here</firstchild>
</root>
如何编辑子元素的文本< firstchild>
?
How do I edit the text of the child element <firstchild>
?
在Qt 4.7中提供的QDomDocument类描述的QDomElement中没有看到任何函数
I don't see any functions in the QDomElement of QDomDocument classes descriptions provided in Qt 4.7
Edit1 - 我要添加更多详细信息。
Edit1 - I am adding more details.
我需要读取,修改和保存xml文件。格式化文件如下 -
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>
元素的值需要编辑。读取xml文件的代码是 -
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);
//读取必要的值
/回写修改的值?
注意:我试图将QDomElement转换为QDomNode并使用函数setNodeValue但它不适用于QDomElement。
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.
推荐答案
p>这将做你想要的(你发布的代码将保持原样):
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.
这篇关于编辑QDomElement的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!