ASP 101 - Active Server Pages 101 - Web06
The Place ASP Developers Go!

Please visit our partners

Windows Technology Windows Technology
15 Seconds
4GuysFromRolla.com
ASP 101
ASP Wire
VB Forums
VB Wire
WinDrivers.com
internet.commerce internet.commerce
Partners & Affiliates














ASP 101 is an
internet.com site
ASP 101 is an internet.com site
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

ASP 101 News Flash ASP 101 News Flash


 Top ASP 101 Stories Top ASP 101 Stories
What is Adovbs.inc and Why Do I Need It?
An Overview of ASP.NET
Connections, Commands, And Procedures

QUICK TIP:
Dragging and dropping a Data Command DTC
Show All Tips >>


An ASP.NET RSS Feed Reader

by John Peterson

Introduction

A few months ago, I published an article (A MegaTokyo RSS Feed Reader) that showed how you could use classic ASP and Microsoft's XML parser to convert an RSS feed into HTML for display on a web page. While the code in that article worked fine, there were two main complaints that I seemed to keep hearing from readers:

  1. It was written in classic ASP and not ASP.NET.
  2. The format of the resulting HTML was a pain to change because I had hard-coded it into the script.

This time around I set out to address both of those issues.

If you're not familiar with RSS, you might find XML Files's RSS section helpful.

An ASP.NET RSS Feed Reader

If I was going to go through the trouble of doing this in ASP.NET, I was going to do it right and, while it is possible, I didn't want to call the COM objects that we used the first time around. This is .NET after all so naturally I wanted to use the .NET Framework's XmlDocument object. Aside from using the .NET object, this part of the script is basically the same. We create an XML object and load an XML file into it either from the remote server or from the file system.

Now to the formatting. Since I was basically starting from scratch anyway, I once again figured that I should take the time and do it right. So instead of all the string parsing and editing I did via VBScript the first time around, this time I set out to create an XSL stylesheet to handle the conversion from the RSS feed's XML format to the desired HTML format. The bad news is that my XSL skills are very weak and, while I knew how to use a stylesheet, actually writing one took me a lot longer than it should have. The good news is that after several tries I finally did get a couple different ones hammered out so you can see how easy it is to change the format of the resulting HTML. All you do is load a different stylesheet... it really couldn't be any simpler.

The last issue that I feel I should mention is that this time around I didn't have to write any caching code. I simply set the page to output cache and presto... instant caching... isn't ASP.NET great!

Why MegaTokyo?

Aside from the fact that they keep changing their format (I miss the thumbnails) and they keep forgetting to update their feed... why not? It's something I read and I want to know when it get's updated. Enough said. For those who haven't yet been there and have no idea what I'm talking about, you might want to visit MegaTokyo.

Despite the fact that I'm using MegaTokyo's feed, there's nothing in the code that should stop you from using it with most any RSS feed. You'll probably need to tweak the XSL files to get your feed to look how you want, but aside from that the script should work with most RSS feeds right "out of the box".

The Code

megatokyo_rss.aspx

<%@ Page Language="VB" Debug="False" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Xml.Xsl" %>
<%@ OutputCache Duration="3600" VaryByParam="none" %>
<script language="VB" runat=server>

  Sub Page_Load(sender As Object, e As EventArgs)

    ' Using a live RSS feed... could also use a cached XML file.
    Dim strXmlSrc  As String = "http://www.megatokyo.com/rss/megatokyo.xml"
    'Dim strXmlSrc As String = Server.MapPath("megatokyo.xml")

    ' Path to our XSL file.  Changing the XSL file changes the
    ' look of the HTML output.  Try toggling the commenting on the
    ' following two lines to give it a try.
    Dim strXslFile As String = Server.MapPath("megatokyo.xsl")
    'Dim strXslFile As String = Server.MapPath("megatokyo2.xsl")

    ' Load our XML file into the XmlDocument object.
    Dim myXmlDoc As XmlDocument = New XmlDocument()
    myXmlDoc.Load(strXmlSrc)

    ' Load our XSL file into the XslTransform object.
    Dim myXslDoc As XslTransform = New XslTransform()
    myXslDoc.Load(strXslFile)

    ' Create a StringBuilder and then point a StringWriter at it.
    ' We'll use this to hold the HTML output by the Transform method.
    Dim myStringBuilder As StringBuilder = New StringBuilder()
    Dim myStringWriter  As StringWriter  = New StringWriter(myStringBuilder)

    ' Call the Transform method of the XslTransform object passing it
    ' our input via the XmlDocument and getting output via the StringWriter.
    myXslDoc.Transform(myXmlDoc, Nothing, myStringWriter)

    ' Since I've got the page set to cache, I tag on a little
    ' footer indicating when the page was actually built.
    myStringBuilder.Append(vbCrLf & "<p><em>Cached at: " _
        & Now() & "</em></p>" & vbCrLf)

    ' Take our resulting HTML and display it via an ASP.NET
    ' literal control.
    litMegaTokyoRssHtml.Text = myStringBuilder.ToString

  End Sub

</script>
<html>
<head>
  <title>ASP 101's ASP.NET MegaTokyo RSS Feed Reader</title>
</head>
<body>

<asp:Literal id="litMegaTokyoRssHtml" runat="server" />

</body>
</html>

Here are the listings for the two included XSL files as well:

megatokyo.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" /> 

  <xsl:template match="/">
    <xsl:for-each select="rss/channel/item">
      <p>
      <a href="{link}"><strong><xsl:value-of select="title" /></strong></a>
      <xsl:value-of disable-output-escaping="yes" select="description" />
      </p>
      <hr />
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

 

megatokyo2.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" /> 

  <xsl:template match="/">

    <xsl:for-each select="rss/channel">
      <h2><a href="{link}"><xsl:value-of select="title" /></a></h2>
    </xsl:for-each>

    <ul>
      <xsl:for-each select="rss/channel/item">
        <li><a href="{link}"><strong><xsl:value-of select="title" /></strong></a></li>
      </xsl:for-each>
    </ul>
  </xsl:template>

</xsl:stylesheet>

The Output

Just so you can see what you'll be getting, here are examples of what the output from each stylesheet looks like:

Sample megatokyo.xsl Output

Comic [614] - "I wish i could start over"

chapter 5, episode 80
[click to read]

[piro]
posted: 09.27.2004 [3:00 Pm EST]


Comic [613] - "but some girls like pathetic dorks"

chapter 5, episode 79
[click to read]

[piro]
posted: 09.24.2004 [11:00 am EST]


Comic [612] - "playing poorly"

chapter 5, episode 78
[click to read]

[piro]
posted: 09.22.2004 [12:34 am EST]


Cached at: 9/28/2004 1:01:00 PM

 

Sample megatokyo2.xsl Output

Megatokyo News

Cached at: 9/28/2004 1:01:00 PM

Download

For those who don't like cutting and pasting, you can download a zip file containing the ASP.NET code and the two XSL files from here: megatokyo_rss_aspx.zip (3.8 KB).

Related Information




Update: How to Show a Limited Number of Items from an RSS Feed

One of the most common questions I receive about the code on this page is how to limit the number of items displayed. For example, let's assume the RSS feed you are pulling in lists the last 20 items published, but you only want to display the 5 most recent items. Luckily, it's relatively easy to do. What's even better is that you can easily do it by creating a modified .XSL file. This means that you can easily display the abbreviated list in one place and the full list in another using the same script just by specifying a different style sheet file.

The change to the XSL files is quite simple. Here are the same two files presented above with the new restriction that limits the number of items displayed to the first 5 highlighted in red.

megatokyo_top5.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" /> 

  <xsl:template match="/">
    <xsl:for-each select="rss/channel/item[position()&lt;=5]">
      <p>
      <a href="{link}"><strong><xsl:value-of select="title" /></strong></a>
      <xsl:value-of disable-output-escaping="yes" select="description" />
      </p>
      <hr />
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

 

megatokyo2_top5.xsl

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="html" /> 

  <xsl:template match="/">

    <xsl:for-each select="rss/channel">
      <h2><a href="{link}"><xsl:value-of select="title" /></a></h2>
    </xsl:for-each>

    <ul>
      <xsl:for-each select="rss/channel/item[position()&lt;=5]">
        <li><a href="{link}"><strong><xsl:value-of select="title" /></strong></a></li>
      </xsl:for-each>
    </ul>
  </xsl:template>

</xsl:stylesheet>

The limiting command just says that the position of the element needs to be less then or equal to 5: [position()<=5]. The problem is that since this command is inside an XML-formatted file, we need to encode the < character as &lt; to prevent it from causing problems.

That's all there is to it. I chose to display the first five items since I figured that would probably be similar to what most people are trying to do, but you can obviously change the criteria to whatever happens to fit your situation.


Home |  News |  Samples |  Articles |  Lessons |  Resources |  Forum |  Links |  Search |  Feedback



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
IBM eBook: Planning a Service Oriented Architecture
IBM eBook: Choosing the Right Architecture--What It Means for You and Your Business
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Avaya Article: Using Intelligent Presence to Create Smarter Business Applications
Intel Go Parallel Article: Getting Started with TBB on Windows
Microsoft Article: 7.0, Microsoft's Lucky Version?
Avaya Article: How to Feed Data into the Avaya Event Processor
IBM Article: Developing a Software Policy for Your Organization
Microsoft Article: Managing Virtual Machines with Microsoft System Center
Intel Go Parallel Article: Intel Threading Tools and OpenMP
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Silverlight 2 App and Walkthrough: Leverage Silverlight 2 with SQL Server and XML
IBM Article: Enterprise Search--Do You Know What's Out There?
HP Demo: StorageWorks EVA4400
Microsoft Article: The Progress and Promise of Deep Zoom
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES