Remove all comments from XDocument

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

I tried with

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

But this only deletes the first level nodes with comments, and the internal level nodes remain as they are.

Is there a way to remove all commented out lines. I think that should be !!!;)

Any decisions.

+4
source share
1 answer

Instead, Where(x => x.NodeType == XmlNodeType.Comment)I would just 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 the 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>

therefore all comments are deleted. If you still have problems, send samples that will allow us to reproduce the problem.

+9

Source: https://habr.com/ru/post/1528255/


All Articles