With LinqToXml, I would like to read the list of albums for a given artist from an XML file, for example
<? 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>
...
I tried the following with LinqToXml. However, I would like to avoid creating an instance of the executing object ...
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;
Update: my current "best" attempt: See Accepted Answer.
source
share