How to remove all comment tags from XML string

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top