开发者

Remove XML Tag using linq c#

开发者 https://www.devze.com 2022-12-27 11:18 出处:网络
I am having on xml from which i have to remove the one book detail <Books> <bookdetail> <bookname>ThreeIdiot</bookname>

I am having on xml from which i have to remove the one book detail

<Books>
  <bookdetail>
    <bookname>ThreeIdiot</bookname>
    <bookauthor>chetan bhagat</bookauthor>
    <bookid>idi001</bookid>
    <isavailable>true</isavailable>
    <subscribername>NA<开发者_如何学Python/subscribername>
  </bookdetail>
  <bookdetail>
    <bookname>Csharp</bookname>
    <bookauthor>Kanitker</bookauthor>
    <bookid>Cshar001</bookid>
    <isavailable>true</isavailable>
    <subscribername>NA</subscribername>
  </bookdetail>
  <bookdetail>
    <bookname>VBbasic</bookname>
    <bookauthor>Andrew Parker</bookauthor>
    <bookid>idi001</bookid>
    <isavailable>true</isavailable>
    <subscribername>NA</subscribername>
  </bookdetail>
</Books>

Now I have to remove the book detail with bookid == Cshar001, Please let me know any Linq command using will search and remove only that tag from the XML.


You can use the XNode.Remove() method for that:

var xDoc = XDocument.Load("myfilename.xml");
var xElement = (
    from x in xDoc.Root.Elements("bookdetail")
    where x.Element("bookid").Value == "Cshar001"
    select x
    ).FirstOrDefault();
xElement.Remove();
xDoc.Save("myfilename.xml");
0

精彩评论

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