Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all comments from XDocument

I am working on reading XDocument. How can I remove all commented lines from XDocument.

I have tried with

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

But this removes only first level nodes with comments and inner level nodes remains as it is.

Is there any way to remove all commented lines. I believe there must be!!! ;)

Any Solutions.

like image 618
Nitin Varpe Avatar asked Feb 22 '14 10:02

Nitin Varpe


1 Answers

Instead of the Where(x => x.NodeType == XmlNodeType.Comment) I would simply use OfType<XComment>(), as in

doc.DescendantNodes().OfType<XComment>().Remove();

but both approaches should remove comment nodes at all levels.

Here is an example:

XDocument doc = XDocument.Load("../../XMLFile1.xml");

doc.Save(Console.Out);

Console.WriteLine();

doc.DescendantNodes().OfType<XComment>().Remove();

doc.Save(Console.Out);

For a sample I get the output

<?xml version="1.0" encoding="ibm850"?>
<!-- comment 1 -->
<root>
  <!-- comment 2 -->
  <foo>
    <!-- comment 3 -->
    <bar>foobar</bar>
  </foo>
  <!-- comment 4 -->
</root>
<!-- comment 5 -->
<?xml version="1.0" encoding="ibm850"?>
<root>
  <foo>
    <bar>foobar</bar>
  </foo>
</root>

so all comments have been removed. If you continue to have problems then post samples allowing us to reproduce the problem.

like image 196
Martin Honnen Avatar answered Sep 17 '22 01:09

Martin Honnen