我需要编辑 QDomElement 的文本 - 例如
我有一个 XML 文件,其内容为 -
<root>
<firstchild>Edit text here</firstchild>
</root>
如何编辑子元素的文本 <firstchild>
?
我在 Qt 4.7 中提供的 QDomDocument 类描述的 QDomElement 中没有看到任何函数
Edit1 - 我正在添加更多细节。
我需要读取、修改和保存一个 xml 文件。文件格式如下-
<root>
<firstchild>Edit text here</firstchild>
</root>
需要编辑element的值。我读取xml文件的代码是-
QFile xmlFile(".\\iWantToEdit.xml"); xmlFile.open(QIODevice::ReadWrite); QByteArray xmlData(xmlFile.readAll()); QDomDocument doc; doc.setContent(xmlData);
// Read necessary values
// write back modified values?
注意:我尝试将 QDomElement 转换为 QDomNode 并使用函数 setNodeValue()。但是它不适用于 QDomElement。
我们非常欢迎任何建议、代码示例、链接。
最佳答案
这将做你想做的(你发布的代码将保持原样):
// 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();
... 一切就绪。您当然也可以写入不同的文件。在此示例中,我只是截断了现有文件并覆盖了它。
关于c++ - 编辑 QDomElement 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6753782/