Removing all nodes of a type from XDocument

  • Thread starter Thread starter graphicsxp
  • Start date Start date
G

graphicsxp

Hello,

I have a XDocument object and I want to remove all the nodes which
name is <comment>. How can I do that ?

Thanks
 
I have a XDocument object and I want to remove all the nodes which
name is <comment>. How can I do that ?

So you want to remove all element nodes named 'comment'? That is done as
follows:
doc.Descendants("comment").Remove();

Here is a sample:

XDocument doc = XDocument.Parse(@"<root>
<comment/>
<foo>
<comment>bar</comment>
</foo>
<comment>
<baz>whatever</baz>
</comment>
<comment>
<comment>foobar</comment>
</comment>
</root>");
doc.Descendants("comment").Remove();
doc.Save(Console.Out);
Console.WriteLine();
 
Try this one:

xDocument.Descendants().Where(e => e.Name == "comment").Remove();
 
So you want to remove all element nodes named 'comment'? That is done as
follows:
   doc.Descendants("comment").Remove();

Here is a sample:

             XDocument doc = XDocument.Parse(@"<root>
   <comment/>
   <foo>
      <comment>bar</comment>
   </foo>
   <comment>
     <baz>whatever</baz>
   </comment>
   <comment>
      <comment>foobar</comment>
   </comment>
</root>");
             doc.Descendants("comment").Remove();
             doc.Save(Console.Out);
             Console.WriteLine();

Thank you, that worked :)
 
Back
Top