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.Element("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”:
Or in non-query expression syntax:
EDIT: If you want all elements descending from
Titles(e.g. to exclude “Book” elements from elsewhere), you’d want: