Перечисление спусков с использованием запроса LINQ - PullRequest
0 голосов
/ 13 мая 2011

Я пытаюсь проанализировать следующие 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 Ответ

5 голосов
/ 13 мая 2011

Я подозреваю, что вы на самом деле хотите найти потомков под названием "Книга", а не "Титулы":

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