Remove all comments from XDocument

喜你入骨 提交于 2020-12-05 05:53:21

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/21952718/remove-all-comments-from-xdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!