开发者

Delete last record/element from existing XML document using LINQ

开发者 https://www.devze.com 2023-03-31 17:12 出处:网络
I have an XML document of the form: <RootEl开发者_StackOverflowement xmlns=\"http://mynamespace\">

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消