How to remove all comment tags from XML string

  • Thread starter Thread starter Andrus
  • Start date Start date
A

Andrus

I need to remove all comments ( between <!-- and --> tags) from XML string.

I tried the following code but comments are still present.
Or is it better to open xml string with a StreamReader, read all the text
inside and remove all the "<!--" and "-->" substrings?

How to remove comments ?


string RemoveComments(string sDoc) {
XmlDocument xDoc = new XmlDocument();
xDoc.PreserveWhitespace = false;
xDoc.LoadXml(sDoc);
XPathNavigator nav = xDoc.CreateNavigator();
while (nav.MoveToNext(XPathNodeType.Comment)) {
nav.DeleteSelf();
}

StringWriter sw = new StringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.IndentChar = ' ';
xtw.Indentation = 2;
xtw.Formatting = Formatting.Indented;

xDoc.WriteContentTo(xtw);
xtw.Close();
sw.Close();
return sw.ToString();
}


Andrus.
 
Back
Top