c++ - 编辑 QDomElement 的值?

标签 c++ qt qt4 qtxml

我需要编辑 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/

相关文章:

c++ - 如何使用 Qt/C++ 创建/读取/写入文件并将设置存储在程序本地

qt4 - 如何在 CMake 中正确链接到 QT4 库?

c++ - 无法输出到 QTextEdit

qt - 如何在Qt中运行系统命令?

c++ - VS c++ compiler on server compiler for free license

c++ - 将字符串映射到 vector 或将不同的键映射到一个值

c++ - 相同的 C++ 代码导致 Windows 上的无限循环和 OSX 上的预期行为

c++ - 如何用boost spirit构建默认值语法?

c++ - 切换 QDeclarativeView 的源

qt - 关于 QML 中不可通知属性的警告