隨着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;
更新:我現在的「最好」的嘗試: 見接受的答案。
感謝您的好評和樂於助人的答案。 – 2009-04-14 06:24:45