Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove XComments from XElement?

Tags:

c#

linq-to-xml

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

from some reason it doesn't work and the 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);
 }

the xml file can be somthing like that

 <user>   
    <name> Elen </name>

    <userSettings>
       <color> blue  </color>                <!-- the theme color of the page -->
       <layout>  horizontal  </layout>      <!-- layout choise -->

       <!-- more settings -->

     </userSettings>

 </user>
like image 959
yoav barnea Avatar asked Feb 05 '13 14:02

yoav barnea


1 Answers

You need to use DescendantNodes instead of Descendants.

Descendants returns XElement instances, so it basically only returns the tags of your XML.
DescendantNodes returns XNode instances, which includes comments.

doc.DescendantNodes().Where(x => x.NodeType == XmlNodeType.Comment).Remove();
like image 162
Daniel Hilgarth Avatar answered Oct 14 '22 04:10

Daniel Hilgarth