how to remove xmlnode within a foreach loop?

前端 未结 5 1832
北荒
北荒 2021-01-07 04:04

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 el

相关标签:
5条回答
  • 2021-01-07 04:30

    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;
    }
    
    0 讨论(0)
  • 2021-01-07 04:36

    The answer, sadly, is to not use foreach, but to fallback on the very bulletproof "for()".

    for(int i = collection.Count - 1; i >= 0; i--)
    {
        object myObject = collection[i];
        collection.Remove(myObject);
    }
    

    In this case, I loop backward in the collection, and remove one object at a time. That way, I can never have an invalid index.

    0 讨论(0)
  • 2021-01-07 04:37

    Use for loop instead from

    for(I=length-1;I>=0;I--)
    

    For each is used for enumerating and you cannot delete while enumerating the list. Also the loop must start from the last element to avoid any shift when you delete an element.

    0 讨论(0)
  • 2021-01-07 04:47

    I found an alterative: Convert xmlnodelist to list<>

    XmlNodeList has a method Cast and can be used as follows:

    var listOfNodes = new List<XmlNode>(xmlNodeList.Cast<XmlNode>());
    
    0 讨论(0)
  • 2021-01-07 04:47

    You are not allowed to change a collection used during a foreach iteration. You can use For..loop instead

    for(int i=0; i<nodeList.Length; i++)
    {
       //remove nodeList[i];
    }
    
    0 讨论(0)
提交回复
热议问题