I am currently looking for a contract in the London area -

If you're hiring a .NET contractor in or around London, look no further!

A YouTube API parser in one line of code


Recently I had to write a simple parser for the YouTube API, to get a list of the videos posted by a user. Not so long ago I would have used XmlDocument, and manually iterated over the result of an XPath query in some nasty looking code.

C# 3.0 and the LINQ project provides us with a new framework for dealing with XML documents - the XDocument.

XDocument allows us to use the Standard Query Operators of LINQ to deal with the objects and collections inside a document, and provides many useful features to a developer. One of the pains I felt with XmlDocument was that dealing with namespaces, using the XmlNamespaceManager, was clunky, and difficult to remember. XDocument (and the rest of the classes in System.Xml.Linq) has much better programmatic support for namespaces. In particular, the overloaded addition operator (+) allows us to easily concatenate namespace prefixes and element names together inline, which leads to much more followable code.

Anyway, on to the code.

The following code snippet shows how easy it is to parse a XML document using XDocument and LINQ - it deserializes the document into a collection of objects in just one line of code.

from feed in doc.Elements("feed")
select new Feed
{
    ID = (string)feed.Element("id"),
    Logo = (string)feed.Element("logo"),
    Title = (string)feed.Element("title"),
    Updated = (DateTime)feed.Element("updated"),
    Author = new Author
    {
        Name = (string)feed.Element("author").Element("name"),
        Uri = (string)feed.Element("author").Element("uri")
    },
    Entries = 
    (
        from entry in feed.Elements("entry")
        select new Entry
        {
            Author = new Author
            {
                Name = (string)entry.Element("author").Element("name"),
                Uri = (string)entry.Element("author").Element("uri")
            },
            Content = (string)entry.Element("content"),
            ID = (string)entry.Element("id"),
            Logo = (string)entry.Element("logo"),
            Title = (string)entry.Element("title"),
            Updated = (DateTime)entry.Element("updated"),
            Url = (string)entry.Elements("link").Attributes().FirstOrDefault
                    (a => a.Value == "alternate").Parent.Attribute("href").Value,
            Media = new Media
            {
                Description = (string)entry.Element("group").Element("description"),
                Keywords = (string)entry.Element("group").Element("keywords"),
                Thumbnails =
                (
                    from thumb in entry.Element("group").Elements("thumbnail") select thumb.Attribute("url").Value
                    
                ),
                Title = (string)entry.Element("group").Element("title"),
            }
        }
    )
}.First();