【问题标题】:Enumerating Descents using LINQ query使用 LINQ 查询枚举下降
【发布时间】:2011-05-13 10:27:10
【问题描述】:

我正在尝试将以下 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();

【问题讨论】:

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


    【解决方案1】:

    我怀疑你实际上想要找到称为“书”而不是“标题”的后代:

    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 */)
    

    【讨论】:

    • @sarat:但是您当前的查询是在寻找称为 Titles的后代...而不是of Titles的后代。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-14
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    相关资源
    最近更新 更多