How to remove XComments from XElement?

I was hoping to remove all XComment from the XElement before sending it to the client.

for some reason it doesn't work and removeMe.Count () = 0

any thoughts?

{ // ... myXml = XElement.Load(myPath); var removeMe=myXml.Descendants().Where(x => x.NodeType == XmlNodeType.Comment); removeMe.Count(); // this is 0 , (not what i was expected) removeMe.Remove(); //... string myResponseStr = myXml.ToString(SaveOptions.None); context.Response.ContentType = "text/plain"; context.Response.Write(myResponseStr); } 

xml file may be the same

  <user> <name> Elen </name> <userSettings> <color> blue </color> <!-- the theme color of the page --> <layout> horizontal </layout> <!-- layout choise --> <!-- more settings --> </userSettings> </user> 
+6
source share
2 answers

You need to use DescendantNodes instead of Descendants .

Descendants returns XElement instances, so it basically returns your XML tags.
DescendantNodes returns XNode instances containing comments.

 doc.DescendantNodes().Where(x => x.NodeType == XmlNodeType.Comment).Remove(); 
+9
source

I would also use DescendantNodes , but instead of calling Where enough to use OfType<XComment>() doc.DescendantNodes().OfType<XComment>().Remove() .

+6
source

All Articles