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();
}

问题原因是:

     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));