Hello all,

Do anyone have any idea of what this Exception in occuring when i try to remove the elements in XML using XmlNodeList.

It occurs in following section :

XmlNodeList nodeLst = xmlDoc.GetElementsByTagName("FileName");

foreach (XmlNode node [B]in[/B] nodeLst)
{
//code
}

Pl help ???

Dani AI

Generated

That exception happens because the XmlNodeList returned by methods like GetElementsByTagName/SelectNodes is “live”: changing the document while a foreach enumerator is walking that list invalidates the enumerator and throws the error. 's quick break after RemoveAll() will stop the crash only when you remove one item and stop, but it’s not a general solution if you need to remove multiple nodes or remove their parent elements.

A safe, common pattern is to iterate the XmlNodeList by index from the end toward the start so removals do not invalidate what you still need to visit:

var nodeList = xmlDoc.GetElementsByTagName("FileName");
for (int i = nodeList.Count - 1; i >= 0; i--)
{
    XmlNode fileNode = nodeList[i];
    XmlNode parent = fileNode.ParentNode;
    if (parent != null && parent.ParentNode != null)
        parent.ParentNode.RemoveChild(parent);   // remove the parent element
    else if (parent != null)
        parent.RemoveChild(fileNode);           // fallback: remove just the file node
}

If multiple FileName nodes share the same parent, removing the parent for the first in a loop can leave others invalid. To handle that, collect unique parents first (using indexing to avoid a live-enumerator) and remove each parent once:

var nodeList = xmlDoc.GetElementsByTagName("FileName");
var parents = new HashSet<XmlNode>();
for (int i = 0; i < nodeList.Count; i++)
    if (nodeList[i].ParentNode != null) parents.Add(nodeList[i].ParentNode);

foreach (var p in parents)
{
    var gp = p.ParentNode;
    if (gp != null) gp.RemoveChild(p);
    else p.RemoveAll(); // if p is root, clear children instead
}

Troubleshooting notes: check for null ParentNode (root items), avoid removing the document element directly unless you intend to replace it, and save the XmlDocument after changes. If the goal is to replace a parent with a new node, consider gp.ReplaceChild(newNode, p) so insertion is atomic.

Recommended Answers

All 3 Replies

Stop the loop - break;

if (node.InnerText == "...")
                {
                    node.ParentNode.RemoveAll();
                    break;
                }

i want to do designing in my visual basic.......i m using c#......plz tell me the different ways......

Thank you so much . It works

Can you tell me how to remove that parent node also so that i can add new node to my xml.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.