2011-05-13 84 views
0

我想解析下列XML文件到列表中。不幸的是,只返回一個元素使用LINQ查詢枚舉Descents

示例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#代碼

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(); 

回答

5

我懷疑你實際上希望被找到後人稱之爲 「書」,而不是 「標題」:

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(); 

或在非查詢表達式中ñ語法:

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(); 

編輯:如果你想所有元素從Titles下降(例如排除來自其他地方的「書」的元素),你會想:

XDocument xmlDoc = XDocument.Load(strXMLPath); 
var books = xmlDoc.Descendants("Titles") 
        .Descendants("Book") 
        .Select(book => /* same as before */) 
+0

@sarat:但是你當前的查詢是尋找後人稱爲* *標題...不是後裔*標題的。 – 2011-05-13 10:34:24