2

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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Iceyoshi
  • 623
  • 3
  • 10
  • 14

2 Answers2

5

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()
jb.
  • 9,921
  • 12
  • 54
  • 90
  • Why `SingleOrDefualt` just remove is enough. – Saeed Amiri Dec 19 '10 at 08:53
  • 1
    @Saeed I prefer know exactly what I'm deleting, Single keeps the code from running Remove() on potentially multiple Snippets, when I only meant this code to remove one. @Henk you are quite right, SingleOrDefault could be null.Remove(), I edited my anwser. – jb. Dec 20 '10 at 02:55
  • @jb, "I prefer know exactly what I'm deleting", So you should surround it with try catch and throw your preferred exception, not just one line of code (because may be there is more than one item). – Saeed Amiri Dec 20 '10 at 05:47
  • Sorry for the late response, but I tested this out and it worked. I also wanted to know what SingleOrDefault meant, then I looked up the MSDN documentation and it said the method would throw an exception if there's more than one of the same element (if the name is the same I guess). So if in this case there is more than one, this probably wouldn't work. Anyway, what is the difference between Single and SingleOrDefault? – Iceyoshi Dec 23 '10 at 12:28
  • @Iceyoshi, Single throws an exception if is more than one item or no item, but SingleOrDefault returns null if is more than one element or no element. – Saeed Amiri Dec 23 '10 at 12:31
  • @Iceyoshi, Also Single() will work in this example because we're only grabbing the Snippets where name="foreach", which there is only one of. – jb. Dec 23 '10 at 17:34
2

You can do it simply, at last you should Save file:

       XDocument doc = XDocument.Load("XmlFile1.xml");
        doc.Descendants("Snippet").Where(p => p.Attribute("name") != null 
                                        && p.Attribute("name").Value == "foreach")
                                        .Remove();
        doc.Save("XmlFile1.xml");
Saeed Amiri
  • 22,252
  • 5
  • 45
  • 83