How to parse WordPress RSS feed using LINQ

Here’s a code snippet of parsing a typical WordPress RSS feed using LINQ. Note, we have to skip the first image from the media element since that’s usually a gravatar of the author.

Everything else is pretty straight forward.

private void BindBlogFeed()
    {
        XDocument doc = XDocument.Load("http://blogworkseverytime.wordpress.com/feed/");
        XNamespace content = "http://purl.org/rss/1.0/modules/content/";
        XNamespace media = "http://search.yahoo.com/mrss/";

        var query = (from feed in doc.Descendants("item")
                     orderby DateTime.Parse(feed.Element("pubDate").Value) descending
                     select new
                     {
                         Title = feed.Element("title").Value,
                         Description = HttpUtility.HtmlDecode(feed.Element("description").Value),
                         Content = HttpUtility.HtmlDecode(feed.Element(content.GetName("encoded")).Value),
                         Image = (from img in feed.Elements(media.GetName("content"))
                                  where img.Attribute("url").Value.Contains("gravatar") == false
                                  select img.Attribute("url").Value).FirstOrDefault() ?? "",
                         Link = feed.Element("link").Value,
                         Date = DateTime.Parse(feed.Element("pubDate").Value).ToShortDateString()
                     });

        lvFirstBlogFeed.DataSource = query.Take(1).ToList();
        lvFirstBlogFeed.DataBind();

        lvRemainingBlogFeed.DataSource = query.Skip(1).ToList();
        lvRemainingBlogFeed.DataBind();
    }
If you liked this post, 🗞 subscribe to my newsletter and follow me on 𝕏!