C# 3.0 and XLinq

I have just been playing around a little with C#3.0 with XLinq trying to see how easy it would be to parse a simple xml document and create a list of strongly type objects out.

I had fun doing this and I will show you what I was doing so that you can either:
a) learn a little of what I learnt
b) tell me where I am going wrong, i.e, if there is a simpler method.

The XML file I am trying to parse is the MusizMox Style XML Document http://musicmoz.org/xml/musicmoz.lists.styles.xml:

<musicmoz>
<style>
<name>A Cappella</name>
<category>Styles/Vocal/A_Cappella</category>
</style>
<style>
<name>Acadian</name>
<category>Styles/World/Cajun/Acadian</category>
</style>
...
...

And I want to produce a List of Name and Categories.

First I created a class as follows:
public class TagCategory
{
public string Name
{
get{return name;}
set{name = value;}
}

public string Category
{
get{return category;}
set{category = value;}
}

private string name;
private string category;
}

This is just a really simple class that holds the tag name and the category of the style.

Now comes the interesting part. The C#3.0 bit. I used XLinq with this, it is only a couple of lines, but it seems to be pretty cool.

Firtly I need to load the XML file, which is simple enough:
XDocument xdoc = XDocument.Load("musicmoz.lists.styles.xml");
XElement root = xdoc.Element("musicmoz");

Now that it is loaded I simple declare a List and run some XLinq as follows:

List t = new List(
root.Elements("style")
.Select(
a => new TagCategory{ Name = a.Element("name").Value,
Category = a.Element("category").Value}
)
);

What I can tell is happening is that we are looking at the root element and pulling back all the "style" elements, then for each element Select all of them but return a new TagCategory using object initilaizers for the Name and the Category class properties.

Clear as mud! :)

Any questions let me know and I will try and answer them :) paul.kinlan@gmail.com

Related Tags
[feed], [feed], [feed], [feed], [feed], [feed], [feed], [feed], [feed]

Related Wikipedia Documents
, , ,

My Related Documents
, , , ,

Related Amazon Books
XML in a Nutshell: / XML Schema: / Xml: Learning by Example: / Link Analysis: An Information Science Approach (Library & Information Science S.): /

Related Images From Flickr
[[posterous-content:iIsFngkrDrebzIgvxIhC]][[posterous-content:IaqpmgrGbcGmhiwGCisD]][[posterous-content:eHtiejdrbJrIHraEIFqh]][[posterous-content:GCIEvGtpElcamlouwrjA]]