Qt使用QDomDocument删除嵌套XML节点后保存文件无变化如何解决
问题原因
- 文件指针位置异常:使用
setContent(&file)读取完整个XML内容后,QFile的读写指针已移动到文件末尾。后续直接执行写入操作时,修改后的XML会被追加到原文件尾部,不会覆盖原有内容,因此直观上看起来文件没有任何变化。 - 代码笔误:示例代码中定义节点变量为
node3,但读取属性时误用了大写开头的Node3,若实际运行中已确认节点能正常删除,可忽略该问题。
修复步骤
- XML内容读取完成后,调用
file.seek(0)将文件指针重置到文件开头位置 - 调用
file.resize(0)清空原文件所有内容,避免修改后的XML长度短于原文件时,尾部残留旧内容 - 修正变量名大小写不一致的笔误
修复后代码
QString filename= QFileDialog::getOpenFileName(this, "Choose File"); if(filename.isEmpty()) return; QFile file(filename); if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) return; QDomDocument xmlBOM; xmlBOM.setContent(&file); // 重置文件指针到开头,清空原有内容 file.seek(0); file.resize(0); QDomNodeList roots = xmlBOM.elementsByTagName("TEST_SCE"); for ( int i = 0; i < roots.count(); i++ ) { QDomElement node = roots.at(i).toElement(); QDomNodeList noderoots = node.elementsByTagName("TEST_SET"); for ( int j = 0; j < noderoots.count(); j++ ) { QDomElement node2 = noderoots.at(j).toElement(); QDomNodeList noderoots2 = node2.elementsByTagName("TEST"); for ( int k = 0; k < noderoots2.count(); k++ ) { QDomNode node3 = noderoots2.at(k); // 修正变量名大小写 unsigned int startFreq = node3.toElement().firstChild().toElement().attribute("start","0").toUInt(); if (startFreq >= 20000000) { node3.parentNode().removeChild(node3); k--; } } } } QByteArray xml = xmlBOM.toByteArray(); file.write(xml); file.close();
内容的提问来源于stack exchange,提问作者DanC225
相关产品推荐
相关产品推荐

