使用linq删除XML标记c#

时间:2010-04-21 10:13:07

标签: c# xml linq

我正在使用xml从中删除一本书的详细信息

<Books>
  <bookdetail>
    <bookname>ThreeIdiot</bookname>
    <bookauthor>chetan bhagat</bookauthor>
    <bookid>idi001</bookid>
    <isavailable>true</isavailable>
    <subscribername>NA</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>

现在我必须使用bookid == Cshar001删除图书详细信息, 请让我知道任何Linq命令使用将搜索并从XML中仅删除该标记。

1 个答案:

答案 0 :(得分:1)

您可以使用XNode.Remove()方法:

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