2009-04-13 73 views
3

隨着LinqToXml我想從一個XML文件中像讀取內部列表與LinqToXml

 
<?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; 

更新:我現在的「最好」的嘗試: 見接受的答案。

回答

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

+0

感謝您的好評和樂於助人的答案。 – 2009-04-14 06:24:45

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(); 
+0

感謝。原始答案幫助我簡化了匿名類型的表達。但目前的答案並沒有給我任何新的東西。我不確定是否在內存中實例化'太多'。 (並不是說它在實際應用中很重要,但我想了解如何最大限度地減少內存使用量。) – 2009-04-13 07:59:01