for 和 while 循环上限值会变化时,特别注意
来源:互联网 发布:字符数组结束标志 编辑:程序博客网 时间:2024/05/09 03:36
这是一个网友遇到的问题:
“xml dom 删除根据节点标签删除节点,为什么老是有一个节点无法删除”
源码如下:
/**
*@function:删除子节点
*@param:
*@author:
*date:
*/
void MainWindow::removeXmlNode(QString fileName,QString tagname)
{
QFile file(fileName);
if( !file.open(QIODevice::ReadOnly))
{
qDebug()<<tr("打开xml文件失败");
return;
}
QDomDocument doc;
if( !doc.setContent(&file))
{
qDebug()<<tr("doc.setContent设置失败!");
file.close();
return;
}
file.close();
QDomNodeList nodeList = doc.elementsByTagName(tagname);
qDebug()<<nodeList.count();
for(int i=0; i<nodeList.count(); i++)
{
QDomElement root = doc.documentElement();
root.removeChild(nodeList.at(i));
}
if( !file.open(QIODevice::WriteOnly))
{
qDebug()<<tr("打开xml文件失败");
return;
}
QTextStream out(&file);
doc.save(out,4);
file.close();
}
*@function:删除子节点
*@param:
*@author:
*date:
*/
void MainWindow::removeXmlNode(QString fileName,QString tagname)
{
QFile file(fileName);
if( !file.open(QIODevice::ReadOnly))
{
qDebug()<<tr("打开xml文件失败");
return;
}
QDomDocument doc;
if( !doc.setContent(&file))
{
qDebug()<<tr("doc.setContent设置失败!");
file.close();
return;
}
file.close();
QDomNodeList nodeList = doc.elementsByTagName(tagname);
qDebug()<<nodeList.count();
for(int i=0; i<nodeList.count(); i++)
{
QDomElement root = doc.documentElement();
root.removeChild(nodeList.at(i));
}
if( !file.open(QIODevice::WriteOnly))
{
qDebug()<<tr("打开xml文件失败");
return;
}
QTextStream out(&file);
doc.save(out,4);
file.close();
}
问题原因是:
root.removeChild(nodeList.at(i));
执行操作之后nodeList.count()值就发生变化了。
所有将for循环的上限值固定住即可。
解决方法1:
QDomNodeList nodeList = doc.elementsByTagName(tagname);
int num=nodeList.count();
for(int i=0; i<num; i++)
{
QDomElement root = doc.documentElement();
root.removeChild(nodeList.at(i));
}
解决方法2:
while (nodeList.count()>0)
{
QDomElement root = doc.documentElement();
root.removeChild(nodeList.at(0));
}
{
QDomElement root = doc.documentElement();
root.removeChild(nodeList.at(0));
}
阅读全文
0 0
- for 和 while 循环上限值会变化时,特别注意
- while和for循环
- while 和 for循环
- while 和 for 循环
- for while循环 列表长度变化
- for循环和while循环
- while循环和for循环
- while和do..while和for循环
- Java循环for, while和do...while
- JavaScript "For"和"While" 循环
- java for循环和while
- for循环和while循环区别。
- shell 中的for循环和while循环
- for循环和while循环的区别
- for 循环和while循环区别
- while循环和for循环的区别
- python while循环和for循环
- Python中的while循环和for循环
- 重写 ccui.text 的clone方法。修复clone字体描边
- IP地址划分问题
- nginx+多个tomcat
- 论人生之转折
- UI文件命名规范常用字
- for 和 while 循环上限值会变化时,特别注意
- 记录一次专线互通后dhcp的问题
- 手动配置project Structure--Idea中使用Git
- recycleview实现title横向滑动,点击条目居中显示
- 实用小软件(gif)
- Qt限制文本框仅输入数字,正则表达式
- 使用aws配置机器学习主机
- Unity3D中Layers和LayerMask解析
- Sublime Text 3 配置 python环境