[英]C# LINQ to XML: number of elements, that have two same attributes?
我有這樣的事情:
<Books>
<Book>
<Number>
<Title>
<Author>
<NumberOfCopies>
</Book>
</Books>
NumberOfCopies
元素表示庫具有相同書籍的相同副本NumberOfCopies
。 (同一本書=同一作者,同一標題)。 每個書的Number
元素都不同,它用於將它們存儲在庫中。
當我添加一本新書時,我想知道該庫有多少副本。(int number)如何做到這一點?
XDocument doc = XDocument.Load("books.xml");
var q = from x in doc.Descendants("Books")
where x.Element("Author").Value == newBook.Author
&& x.Element("Title").Value == newBook.Title
select x;
int number = (int)q;
這不起作用。 我究竟做錯了什么?
我懷疑你想要:
var book = doc.Descendants("Book") // Note Book, not Books
.Where(x => x.Element("Author").Value == newBook.Author &&
x.Element("Title").Value == newBook.Title)
.FirstOrDefault();
if (book != null)
{
int copies = (int) book.Element("NumberOfCopies");
}
當然,這假設您只有一個給定書籍的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.