使用LINQ查询枚举Descents

sar*_*rat 0 c# linq linq-to-xml c#-3.0 c#-4.0

我试图将以下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>
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 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();
Run Code Online (Sandbox Code Playgroud)

或者在非查询表达式语法中:

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();
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想要所有元素降序Titles(例如从其他地方排除"Book"元素),你需要:

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