Dec 4, 2007

Maybe a candidate for Mono.Rocks

Answering a thread on XmlNodeList manipulation on the list I came with this answer and (untested) Mono.Rocks candidate:

As a fan of generics I would create a helper class (based on Robert Jordan code):


public class XmlNodeListHelper
{
public static List CopyNodeList(XmlNodeList list)
{
List copy = new List();

foreach (XmlNode node in list)
copy.Add (node);
return copy;
}

public static void RemoveNodes(XmlNodeList list)
{
foreach (XmlNode node in CopyNodeList(list))
node.ParentNode.RemoveChild(node);
}
}


And so the code in question would become just:


XmlNodeListHelper.RemoveNodes(xDoc.SelectNodes("//comment()"));


When using the latest compilers it could be made into a Mono.Rocks helper like:


public class XmlNodeListHelper
{
public static List CopyAsList(this XmlNodeList list)
{
List copy = new List();

foreach (XmlNode node in list)
copy.Add (node);

return copy;
}

public static void RemoveNodes(this XmlNodeList list)
{
foreach (XmlNode node in list.CopyAsList())
node.ParentNode.RemoveChild(node);
}
}


And then usage would be even simpler


Doc.SelectNodes("//comment()").RemoveNodes();

No comments: