C#LINQ to XML:具有两个相同属性的元素数?
我有这样的想法:C#LINQ to XML:具有两个相同属性的元素数?,c#,xml,linq,C#,Xml,Linq,我有这样的想法: <Books> <Book> <Number> <Title> <Author> <NumberOfCopies> </Book> </Books> 这不管用。我做错了什么?我怀疑你想要: var book = doc.Descendants("Book") // Note Book, not Book
<Books>
<Book>
<Number>
<Title>
<Author>
<NumberOfCopies>
</Book>
</Books>
这不管用。我做错了什么?我怀疑你想要:
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");
}
当然,这假设给定的书只有一个元素。请向我们展示实际的XML—我们无法在这里说明结构。(特别是,您已经讨论了属性,但我们看不到任何…)一个简单的强制转换是否适用于
.Element(name)
?你不需要真正解析它吗?@J.Steen:是的,它会工作的。XElement.Sweet有显式转换。我还没有在这些课程上做很多。很高兴知道。
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");
}