仅使用LinqToXml读取内部列表

时间:2009-04-13 05:54:49

标签: c# linq linq-to-xml

使用LinqToXml我想从xml文件中读出给定艺术家的专辑列表,如

<?xml version="1.0" encoding="utf-8" ?>
<artists>
  <artist name="Beatles">
    <albums>
      <album title="Please Please Me" year="1963"/>
      <album title="With the Beatles" year="1963"/>
      ...
    </albums>
  </artist>
  ...

我尝试使用LinqToXml进行以下操作。但是,我想避免实例化艺术家对象......

XDocument xartists = XDocument.Load(FilePhysicalPath);
var artists = from xartist in xartists.Descendants("artist")
              where xartist.Attribute("name").Value.Equals(id)
              select new MusicArtist
              {
                  Albums = from xalbum in xartist.Descendants("album")
                           select new MusicAlbum
                           {
                               Title = xalbum.Attribute("title").Value,
                               Year =
                               int.Parse(xalbum.Attribute("year").Value)
                           }
              };
var artist = artists.SingleOrDefault();
if (artist != null)
    return artist.Albums;
else
    return null;

更新:我目前的“最佳”尝试: 请参阅接受的答案。

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

    return (from artist in 
                     (from xartist in xartists.Descendants("artist")
                     where xartist.Attribute("name").Value.Equals("Beatles")
                     select new MusicArtist
                     {
                         Albums = from xalbum in xartist.Descendants("album")
                                  select new MusicAlbum
                                  {
                                      Title = xalbum.Attribute("title").Value,
                                      Year =  int.Parse(xalbum.Attribute("year").Value)
                                  }
                     })
                  where artist != null
                 select artist).FirstOrDefault();

答案 1 :(得分:1)

应该是这样的:

var result = from artist in xartists.Root.Elements("artist")
             where artist.Attribute("name").Value.Equals(id)
             let albums = artist.Element("albums")
             from album in albums.Elements("album")
             select new MusicAlbum
             {
                 Title = album.Attribute("title").Value,
                 Year = (int) album.Attribute("year")
             };

请特别注意使用Element / Elements代替Descendents