从XDocument删除所有评论 [英] Remove all comments from XDocument

查看:57
本文介绍了从XDocument删除所有评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读XDocument.如何从XDocument删除所有注释行.

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

我尝试过

 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!!! ;)

任何解决方案.

推荐答案

而不是 Where(x => x.NodeType == XmlNodeType.Comment)我会简单地使用 OfType< XComment>(),如

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.

这里是一个例子:

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

doc.Save(Console.Out);

Console.WriteLine();

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

doc.Save(Console.Out);

对于示例,我得到输出

<?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.

这篇关于从XDocument删除所有评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆