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 t开发者_JAVA百科o 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()
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");
精彩评论