我需要编辑QDomElement的文本 - 例如
我有一个XML文件,其内容为 -
<root>
<firstchild>Edit text here</firstchild>
</root>
Run Code Online (Sandbox Code Playgroud)
如何编辑子元素的文本<firstchild>?
我在Qt 4.7中提供的QDomDocument类描述的QDomElement中没有看到任何函数
Edit1 - 我正在添加更多细节.
我需要读取,修改和保存xml文件.格式化文件如下 -
<root>
<firstchild>Edit text here</firstchild>
</root>
Run Code Online (Sandbox Code Playgroud)
元素的值需要编辑.我读取xml文件的代码是 -
Run Code Online (Sandbox Code Playgroud)QFile xmlFile(".\\iWantToEdit.xml"); xmlFile.open(QIODevice::ReadWrite); QByteArray xmlData(xmlFile.readAll()); QDomDocument doc; doc.setContent(xmlData);//读取必要的值
//回写修改后的值?
注意:我尝试将QDomElement强制转换为QDomNode并使用函数setNodeValue().但它不适用于QDomElement.
我们非常欢迎任何建议,代码示例,链接.
Luc*_*uke 19
这将做你想要的(你发布的代码将保持原样):
// 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();
Run Code Online (Sandbox Code Playgroud)
......你们都准备好了.你当然也可以写一个不同的文件.在这个例子中,我只是截断了现有文件并覆盖了它.
当您想更改节点内的文本时,只是为了使用更好更简单的解决方案(类似于 Lol4t0 所写)更新它。'firstchild' 节点内的文本实际上变成了一个文本节点,所以你要做的是:
...
QDomDocument doc;
doc.setContent(xmlData);
doc.firstChildElement("firstchild").firstChild().setNodeValue(??"new text");
Run Code Online (Sandbox Code Playgroud)
注意额外的 firstChild() 调用,它将实际访问文本节点并使您能够更改值。这比创建新节点和替换整个节点要简单得多,而且肯定更快,侵入性更小。