July 6, 2017

How to remove all comment tags from XmlDocument

In this post I will share C# code to remove comments from XML string or file. I am using XMl file in this example: I found two possible ways to achieve this.

Lets say we need a function named RemoveCommentsFromXMLFile(string sourceFilePath, string destinationFilePath), which reads xml from source file and then save a copy of same xml content to destination file after removing comments.

  • Remove comments from XML content before loading from a source.

    public static void RemoveCommentsFromConfigFile(string sourceFilePath, string destinationFilePath)
    {
     XmlReaderSettings readerSettings = new XmlReaderSettings();
     readerSettings.IgnoreComments = true; //set this flag in readsettings to read xml without comments.
    
     XmlReader reader = XmlReader.Create(sourceFilePath, readerSettings);
    
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.Load(reader);
     reader.Close();
     xmlDoc.Save(destinationFilePath);
    }
    
  • Remove comments from XML content after loading from a source.

    public static void RemoveCommentsFromConfigFile(string sourceFilePath, string destinationFilePath)
    {
     System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
     xmlDoc.Load(sourceFilePath);
    
     System.Xml.XmlNodeList list = xmlDoc.SelectNodes("//comment()");
    
     foreach (System.Xml.XmlNode node in list)
     {
      node.ParentNode.RemoveChild(node);
     }
    
     xmlDoc.Save(destinationFilePath);
    }
    

2 comments: