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: