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 learntb) 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

I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

I love to learn about what you are building, and how I can help with Chrome or Web development in general, so if you want to chat with me directly, please feel free to book a consultation.

I'm trialing a newsletter, you can subscribe below (thank you!)