使用LINQ查询枚举Descents

时间:2011-05-13 10:27:10

标签: c# linq c#-4.0 c#-3.0 linq-to-xml

我正在尝试将以下XML文件解析为列表。不幸的是,它只返回一个元素

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

1 个答案:

答案 0 :(得分:5)

我怀疑你实际希望找到名为“Book”而非“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();

或者使用非查询表达式语法:

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下降(例如从其他地方排除“Book”元素),您需要:

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