views:

282

answers:

3

How would i go about to remove all comment tags from a XmlDocument instance?

Is there a better way than retrieving a XmlNodeList and iterate over those?


    XmlNodeList list = xmlDoc.SelectNodes("//comment()");

    foreach(XmlNode node in list)
    {
        node.ParentNode.RemoveChild(node);
    }
+2  A: 

Nope thats about it, although I'd be inclind to place the nodes in a List first.

I'm not sure about the .NET implementation of XmlNodeList but I know that previous MSXML implementations loaded the list in lazy manner and code such as the above in the past would end up failing in some way as result of the DOM tree being modified as the List is enumerated.

 foreach (var node in xml.SelectNodes("//comment()").ToList())
   node.ParentNode.RemoveChild(node);
AnthonyWJones
+6  A: 

When you load the xml, you can use XmlReaderSettings

XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;
XmlReader reader = XmlReader.Create("...", settings);
xmlDoc.Load(reader);

On an existing instance, your solution looks good.

Guillaume
A: 

Try also this solution.

tunnuz