gpt4 book ai didi

C# Xml 到 Linq 删除一个项目

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:28 25 4
gpt4 key购买 nike

我正在尝试将带有 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>

删除项目

我正在尝试导航到特定元素,然后调用 .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);
}

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

提前致谢

最佳答案

我建议使用 Element 而不是 Elements,并将 XElement 转换为 string 而不是使用 。结合使用 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();

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

要考虑的另一种选择是只是匹配 ISBN - 这实际上是图书的标识符,不是吗?如果您的书碰巧有不同的价格,或者作者有不同的标点符号,您是否肯定希望这样做以防止被删除?

关于C# Xml 到 Linq 删除一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32371123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com