Aug 18

Consuming a (delicious) RSS Feed Using LINQ to XML

An example of using LINQ to XML for consuming an RSS feed

Once I implemented blog posts and comments, I needed something to fill up all the empty space on the right. So, I decided to list out my recent delicious bookmarks. I had been wanting to play around with LINQ to XML, and this was a perfect use for it.

I first created a DeliciousLink POCO class with the three properties I was interested in: Title, Url, and Description. This is all I need to create the bookmark list.

I then added a new method to one of my Service classes. This method loads my delicious rss feed and then loops through the items creating a list of DeliciousLink's:

public IEnumerable<DeliciousLink> GetDeliciousLatest(int quantity) {

    XDocument rssFeed = XDocument.Load("");

    return from item in rssFeed.Descendants("item")
            select new DeliciousLink
                Title = item.Element("title").Value,
                Url = item.Element("link").Value,
                Description = (item.Element("description") != null) ? item.Element("description").Value : ""

Then I created a controller Action that retrieves and caches the links using the service. This action can then be called by any View using the Html.RenderAction method.

public ActionResult GetDeliciousLatest(int quantity) {
    IEnumerable<DeliciousLink> posts = HttpContext.Cache["DELICIOUS_LINKS"] as IEnumerable<DeliciousLink>;
    if (posts == null) {
        try {
            posts = _miscService.GetDeliciousLatest(quantity);
            HttpContext.Cache.Insert("DELICIOUS_LINKS", posts, null, DateTime.Now.AddMinutes(15), System.Web.Caching.Cache.NoSlidingExpiration);

        } catch { }

    return View("_Delicious", posts.Take(quantity));

The last piece was to create _Delicious.aspx, which is a Partial View.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="_Delicious.aspx.cs" Inherits="rr.web.Views.Misc._Delicious" %>
<% foreach ( link in ViewData.Model) { %>
  <a href="<%= Html.AttributeEncode(link.Url) %>" title="<%= Html.AttributeEncode(link.Description) %>">
  <%= Html.Encode(link.Title) %>
<% } %>

This ended up being a lot easier than I thought it would be. No tedious XML parsing was necessary :).

This is already my fifth post so I am going to have to implement paging soon!

Powered by my hackings on Django-Mingus a Django project, PostgreSQL, memcached, nginx, Apache + mod_wsgi, Ubuntu, Rackspace Cloud,...

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

html5 | top