Monday, 3 August 2009

Using ASP to display RSS feed with images from BBC news

I have been puzzling how to retrieve an RSS feed into a page of another webiste using classic ASP (in PHP I can heartily recommend the use of SimplePie)

I found some code which allowed me to get the list of items and links using XSLT to transform the retrieved XML - but had to do a bit more delving to find a way of dispalying the image thumbnails that you get in the more advanced RSS feeds.

Below is my solution:

This is the XSL stylesheet - call rssStyle.xslt:

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:media="http://search.yahoo.com/mrss">
<xsl:output method="html" omit-xml-declaration="yes" />
<xsl:template match="/">
<xsl:for-each select="rss/channel/item[position()&lt;=3]">
<div class="newsItem">
<a>
<xsl:attribute name="href">
<xsl:value-of select="link" />
</xsl:attribute>
<xsl:attribute name="target">_blank</xsl:attribute>
<img>
<xsl:attribute name="src">
<xsl:value-of select="media:thumbnail/@url" disable-output-escaping="yes" />
</xsl:attribute>
</img>

</a>

<h3 class="highlight"><a>
<xsl:attribute name="href">
<xsl:value-of select="link" />
</xsl:attribute>
<xsl:attribute name="target">_blank</xsl:attribute>
<xsl:value-of select="title" disable-output-escaping="yes" />
</a>
</h3>

<p>
<xsl:value-of select="description" disable-output-escaping="yes" />
</p>

</div>

</xsl:for-each>
</xsl:template>

</xsl:stylesheet>



This bits in bold are respectively

1) The neamespace decalration to allow you to read teh media:thumbnail element

2) The test that allows you to show only the first 3 stories from feed

3) The code that actually shows the thumbnail image



Here is the code for the ASP page that shows the news feed - I'm using it as an include in another ASP page - but you can just get it to create the whole html page by uncommneting out the lines that write the header and footer of teh HTML page:

<%
response.ContentType="text/html"
dim objXML, objXSL
set objXML=server.CreateObject("MSXML2.DOMDocument")
set objXSL=server.CreateObject("MSXML2.DOMDocument")
objXML.async=False
objXSL.async=False
objXML.setProperty "ServerHTTPRequest",true
objXML.load "http://newsrss.bbc.co.uk/rss/newsplayer_uk_edition/business/rss.xml"
objXSL.load Server.MapPath("rssStyle.xslt")
'response.write "<html><head><title>RSS Feed Reader</title></head><body>"
response.write "<h2 id=""busNewsHead"">Latest Business News</h2>"
response.write "<p class=""small"">&copy; BBC News 2009</p>"
response.write "<div id=""businessNews"">"
response.write objXML.transformNode(objXSL)
response.write "</div>"
'response.write "</body></html>"
set objXML=nothing
set objXSL=nothing
%>

0 comments:

Post a Comment