如何在foreach循环中删除xmlnode? [英] how to remove xmlnode within a foreach loop?

查看:64
本文介绍了如何在foreach循环中删除xmlnode?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,我使用foreach循环来检查nodelist中的每个节点并删除其中的一些节点.我删除一个节点后,foreach循环会引发以下错误:元素列表已更改.枚举操作无法继续".我该如何避免呢?

 公共静态XmlNodeList扫描(XmlNodeList nodeList){字符串elementValue = null;foreach(nodeList中的XmlNode xmlElement){elementValue = xmlElement.InnerText;if(elementValue.Length> = 6&& elementValue.Substring(0,3)=="999"){继续;}别的{XmlNode节点= xmlElement.ParentNode;node.RemoveChild(xmlElement);}}返回nodeList;} 

解决方案

由于您不是简单地从要循环访问的集合中删除项目,因此不确定使用for循环"是否会起作用./p>

以下步骤分为两个步骤:

  1. 创建一个常规列表,列出要与父母分离的所有元素.
  2. 通过遍历常规列表(不受分支影响)来从其父级中删除这些元素.

 公共静态XmlNodeList扫描(XmlNodeList nodeList){列表< XmlNode>toRemove = new List< XmlNode>();foreach(nodeList中的XmlNode xmlElement){字符串elementValue = xmlElement.InnerText;if(elementValue.Length< 6 || elementValue.Substring(0,3)!="999"){toRemove.Add(xmlElement);}}foreach(toRemove中的XmlNode xmlElement){XmlNode节点= xmlElement.ParentNode;node.RemoveChild(xmlElement);}返回nodeList;} 

At the following code i use foreach loop to check each node in nodelist and remove some of them. after i remove one node the foreach loop throw the following error: "The element list has changed. The enumeration operation failed to continue". How can i avoid it?

public static XmlNodeList Scan(XmlNodeList nodeList)
        {
            string elementValue = null;
            foreach (XmlNode xmlElement in nodeList)
            {
                elementValue = xmlElement.InnerText;
                if (elementValue.Length >= 6 && elementValue.Substring(0, 3) == "999")
                {
                    continue;
                }
                else 
                {
                    XmlNode node = xmlElement.ParentNode;
                    node.RemoveChild(xmlElement);
                }
            }

            return nodeList;
        }

解决方案

As you're not simply removing items from the collection you're looping over, I'm not sure if "use a for loop" will work.

The following takes two steps:

  1. Create a regular list of all the elements you want to detach from their parents.
  2. Detatch those elements from their parents - by iterating over the regular list, which isn't affected by the detachings.

public static XmlNodeList Scan(XmlNodeList nodeList)
{
    List<XmlNode> toRemove = new List<XmlNode>();

    foreach (XmlNode xmlElement in nodeList)
    {
        string elementValue = xmlElement.InnerText;
        if (elementValue.Length < 6 || elementValue.Substring(0, 3) != "999")
        {
            toRemove.Add(xmlElement);
        }
    }

    foreach(XmlNode xmlElement in toRemove)
    {
        XmlNode node = xmlElement.ParentNode;
        node.RemoveChild(xmlElement);
    }

    return nodeList;
}

这篇关于如何在foreach循环中删除xmlnode?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆