Search code examples
c#linq-to-xmlcode-snippets

XDocument deleting a node


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>

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.


Solution

  • 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()