how to remove xmlnode within a foreach loop?

前端 未结 5 1963
北荒
北荒 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 toRemove = new List();
    
        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;
    }
    

提交回复
热议问题