Remove all comments from XDocument
c#-4.0, linq-to-xml
Solution
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.
Problem
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.