Delete last record/element from existing XML document using LINQ
I have an XML document of the form:
<RootEl开发者_StackOverflowement xmlns="http://mynamespace">
<MyElement>
<ElementNumber>0</ElementNumber>
<Data>mydata</Data>
<MoreData>more my data</MoreData>
</MyElement>
<MyElement>
<ElementNumber>1</ElementNumber>
<Data>mydata 2</Data>
<MoreData>more my data 2</MoreData>
</MyElement>
</RootElement>
I want to remove the LAST MyElement
record. That is, the one with the ElementNumber
containing the data of "1"
. I will ALWAYS need to remove the last MyElement
record in my XML file, in case that helps.
Simple:
var xmlPath = @"C:\path\to\file.xml";
var doc = XDocument.Load(xmlPath);
XNamespace ns = "http://mynamespace";
var removeMe = doc.Descendants(ns + "MyElement").LastOrDefault();
if (removeMe != null)
removeMe.Remove();
// uncomment when ready to save
//doc.Save(xmlPath);
精彩评论