Monday, July 13, 2009

Consuming an RSS feed using LinqToXml

I needed to display some RSS feeds into a dashboard page in one of our websites. I figured I had to mess with XML, XPath, etc.. to browse the xml structure of the post. However, LinqToXml turned out to be the perfect tool for this task. I used Scottgu’s post as a reference, but did my own little twist at the end to avoid another “loop”

First, pass the Rss feed Url into an Xdocument variable:


Dim feedXml As XDocument = _
XDocument.Load(“http://feeds2.feedburner.com/AppriverMalwareWatch”)

Now I need to iterate through the “item” children tags in the XML document and get the “link”, “title” , and “pubDate” elements. Also, I am going to display each post as a hyperlink in an unordered list with the date next to it. Finally, I only need the most recent 8 posts. Here is where magic of LINQ comes in handy:

Dim myFeeds = From feed In feedXml.Descendants("item") Select _
<li>
<a target="_blank" href=<%= feed.Element("link").Value %><%= feed.Element("title").Value %>
</a><%= Date.Parse(feed.Element("pubDate").Value).ToString("M/dd") %>
</li> _
Take 8

'Add xElements to the String literal
Dim myUL = <ul>
<%= myFeeds %>
</ul>

Now that I have added the feeds to my unordered list, I need to write the html to the div container:


'Write string literal to Div's body
Me.uxDivUls.InnerHtml = myUL.ToString

That's it. In a few lines of code I was able to Consume an Rss Feed. What is there not to love about linq to xml??

Happy coding!

No comments: