C#Xml到Linq删除一个项目

xer*_*him 1 .net c# xml linq

我正在尝试将带有xml的项目移除到linq,但我无法让它工作:

XML

<books>
    <book>
        <title>Harry Potter und der Stein der Waisen</title>
        <isbn>1</isbn>
        <author>J. K. Rowling</author>
       <price>30</price>
    </book>
</books>
Run Code Online (Sandbox Code Playgroud)

DeleteItem

我正试图导航到特定元素,然后调用 .Remove()

public void DeleteItem(Book toRemove)
{
  var xmlDoc = this.xmlFileStorage.LoadXmlDocument();
  xmlDoc
      .Descendants("books")
          .Elements("book")
              .Where(x => 
                  x.Elements("title").Single(y => y.Value == toRemove.Title)
                        && x.Elements("author").Single(y => y.Value == toRemove.Author)
                        && x.Elements("isbn").Single(y => y.Value == toRemove.Isbn)
                        && x.Elements("price").Where(y => y.Value == toRemove.Price.ToString()))
                    .Remove();

    this.xmlFileStorage.SaveXmlDocument(xmlDoc);
}
Run Code Online (Sandbox Code Playgroud)

我不认为这.Single()是正确的方法......我如何从xml文档中获取确切的记录?

提前致谢

Jon*_*eet 5

我会建议使用Element的替代Elements,以及铸造XElement,以string代替使用Value.结合使用Title而不是title和它应该没关系:

xmlDoc.Descendants("books")
      .Elements("book")
      .Where(x => (string) x.Element("title") == toRemove.Title
               && (string) x.Element("author") == toRemove.Author
               && (string) x.Element("isbn") == toRemove.Isbn
               && (string) x.Element("price") == toRemove.Price)
      .Remove();
Run Code Online (Sandbox Code Playgroud)

当然,这将删除所有匹配的元素.如果你想确保只有一个比赛,你可以调用SingleOrDefault(),检查结果不为空,然后调用RemoveXElement.

考虑另一种选择是匹配在ISBN -这就是有效地为这本书的标识,不是吗?如果你的书碰巧有不同的价格,或者作者有不同的标点符号,你是否真的希望这样做以防止删除?