I have two classes - Cd and Track which I'm trying to read into from a XML file using Linq.
public Cd(string t, string a, string cat, DateTime rls, Track[] tr)
public Track(string t, int l)
The XML looks like this.
<media>
<cd>
<artist>Ozzy Osbourne</artist>
<album Name="Bark at the moon" Type="Metal" Tracks="5" ReleaseDate="1983-12-10">
<track Length="300">Bark at the moon</track>
<track Length="235">You're No Different</track>
<track Length="567">Now You See It (Now You Don't)</track>
<track Length="356">Rock 'N' Roll Rebel</track>
<track Length="120">Centre of Eternity</track>
</album>
</cd>
<cd>
<artist>Journey</artist>
<album Name="Escape" Type="Rock" Tracks="4" ReleaseDate="1981-07-31">
<track Length="300">Don't Stop Believin'</track>
<track Length="235">Stone in Love</track>
<track Length="567">Who's Crying Now</track>
<track Length="356">Keep on Runnin'</track>
</album>
</cd>
</media>
The code I'm trying to use is as follows
XElement xdoc = XElement.Load("dbxml.xml");
var temp = from cds in xdoc.Descendants("cd")
select new Cd(
cds.Element("artist").Value,
cds.Element("album").Attribute("Name").Value,
cds.Element("album").Attribute("Type").Value,
DateTime.Parse(cds.Element("album").Attribute("ReleaseDate").Value),
new Track[] { // One Track reads fine..
new Track(cds.Element("album").Element("track").Value,
int.Parse(cds.Element("album").Element("track").Attribute("Length").Value))
}
);
The problem is that I don't know how to initialize the array with all the tracks read from the XML file. I could wrap the whole query in a .ToList(), use an anonomyous type and foreach-it but I'd like to know if there is a way to do this in just one run with linq.
cds.Elements("album").Elements("song") returns an IEnumerable<XElement> collection and somehow that should be added to the array as a range and turned into a string and an int, or something to that affect. Any help out there?
Thanks!
This would work:
Easier to read (imo) using properties:
You should consider adding a default constructor to
CdandTrackand exposing public properties or use named parameters - this would make the LINQ statement much more readable.