XDocument删除节点 [英] XDocument deleting a node

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

问题描述

如何从已加载的XDocument中删除特定节点?我的XML文档如下所示:

How do I delete a specific node from a loaded XDocument? My XML document looks like this:

<Snippets>
  <Snippet name="if">
    <SnippetCode>      
 if (condition)
 {
 }
    </SnippetCode>
</Snippet>

<Snippets>
  <Snippet name="foreach">
    <SnippetCode>      
 ...
    </SnippetCode>
</Snippet>

....

</Snippets>

所以说如果我只想删除foreach片段,那我该怎么做?我尝试了doc.Descendants.Remove(),但对我来说不起作用(该节点未删除).

So say if I wanted to delete just the foreach snippet, how would I do that? I tried doc.Descendants.Remove(), but it didn't work for me (the node didn't get deleted).

编辑-关于这一点,我如何重命名代码段并通过代码编辑代码段?我尚未对此进行调查,但是会有所帮助.

Edit - on that note, how can I also rename the snippet and edit the snippets through code? I haven't looked into that yet but some help would be appreciated.

推荐答案

未经测试,但这应该可行.让我知道是否要解释它.

untested, but this should work. Let me know if you want it explained.

xdoc.Descendents("Snippet").Where(xe => xe.Attribute("name") != null 
    && xe.Attribute("name").Value == "foreach").Single().Remove()

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

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