Enumerating Descents using LINQ query
I am trying to parse the following XML files in to a list. Unfortunately it returns only one element
Sample XML
<Titles>
<Book Title ="Love Story" Author= "Erich Segal" Year = "1999"/>
<Book Title ="Code Complete" Author= "Steve McConnel" Year = "2004"/>
<Book Title ="Rework" Author = "Jaso Fried" Year = "2010"/>
<Book Title ="Delivering Happiness" Author= "Tony Hseigh" Year = "2011"/>
</Titles>
C# Code
public class BookInfo
{
public string Title { get; set; }
public string Author { get; set; }
public int Year { get; set; }
}
XDocument xmlDoc = XDocument.Load(strXMLPath);
var b = from device in xmlDoc.Descendants("Titles")
select new BookInfo
{
Title = device.Element("Book").Attribute("Title").Value,
Author = device.E开发者_如何学编程lement("Book").Attribute("Author").Value,
Year = int.Parse(device.Element("Book").Attribute("Year").Value)
};
books = b.ToList();
I suspect you actually want to be finding descendants called "Book" rather than "Titles":
XDocument xmlDoc = XDocument.Load(strXMLPath);
var b = from book in xmlDoc.Descendants("Book")
select new BookInfo
{
Title = (string) book.Attribute("Title"),
Author = (string) book.Attribute("Author"),
Year = (int) book.Attribute("Year")
};
var books = b.ToList();
Or in non-query expression syntax:
XDocument xmlDoc = XDocument.Load(strXMLPath);
var books = xmlDoc.Descendants("Book")
.Select(book => new BookInfo
{
Title = (string) book.Attribute("Title"),
Author = (string) book.Attribute("Author"),
Year = (int) book.Attribute("Year")
})
.ToList();
EDIT: If you want all elements descending from Titles
(e.g. to exclude "Book" elements from elsewhere), you'd want:
XDocument xmlDoc = XDocument.Load(strXMLPath);
var books = xmlDoc.Descendants("Titles")
.Descendants("Book")
.Select(book => /* same as before */)
精彩评论