Removing of nodes in XmlDocument

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives


There are many business cases which requires you look for some specific data in some collection and finally to remove them from the collection.

For example, consider following code:

public static void RemoveItems(){

List<string> items = new List<string>();
items.Add("Item1");
items.Add("Item2");
items.Add("Item3");

foreach (string item in new List<string>(items))
{
   if(item == "Item2")
   items.Remove(item);
}

This code is a bad example, because when executed, following exception will be thrown:

Collection was modified; enumeration operation may not execute.

This means that no enumeration in foreach loop is allowed, while collection is modified. To solve the problem the code can be slightly changed as shown bellow:

Now, consider following code, which removes some specific nodes from XmlDocument.

public static void RemoveNodesOk()
{

XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"Y:\Test.Xml");

XmlNodeList nodeList = dataDoc.SelectNodes(…);

foreach (XmlNode node in nodeList)
{

XmlNode distNode = node.SelectSingleNode("DistributorID");

if (distNode != null)
{
  if (distNode.InnerText == "DAMIR")
  {
      
xDoc.DocumentElement.RemoveChild(node);
  }
}

}

xDoc.Save(@"D:\TestOut.Xml");

}

public static void RemoveNodesBad()
{

XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"Y:\Test.Xml");

foreach (XmlNode node in xDoc.DocumentElement.ChildNodes)
{

XmlNode distNode = node.SelectSingleNode("DistributorID");

if (distNode != null)
{
  if (distNode.InnerText == "DAMIR")
  {
      
xDoc.DocumentElement.RemoveChild(node);
  }
}

}

xDoc.Save(@"D:\TestOut.Xml");

}

What do you think ehat happen when this code is executed? Probably the same exception is thrown. Unfortinately this is not a true. This code will enters a loop as long the first item is found with the DistributorID = “DAMIR”. Then, after the first found item is removed, the loop wil just exit. Funny? Personally, I do not find it funny.

Following function shows how to do that the right way:


Posted Dec 12 2006, 05:40 PM by Damir Dobric
Filed under:
developers.de is a .Net Community Blog powered by daenet GmbH.