Search code examples
c#.netxmldocument

How to remove all comment tags from XmlDocument


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);
    }

Solution

  • 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.