Sunday, August 10, 2008

Reading RSS from Blogger, display to ASP.NET

Blogger use 2 type of syndication :
  • RSS 2.0
  • Atom
to read and display it to ASP.NET, I use XSLT to transform the RSS into HTML.
below is a sample of my XSLT file.

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html">
<xsl:template match="/">
<style>
<xsl:comment>
</xsl:comment>
</style>
<xsl:apply-templates select="/rss/channel">
</xsl:template>
<!-- Blogger Information -->
<xsl:template match="/rss/channel">
<div class="blogreader">
<h1>
<a href="{link}">
<xsl:value-of select="title">
</a>
</h1>
<xsl:apply-templates select="item">
</div>
</xsl:template>
<!--Blogger Items-->
<xsl:template match="/rss/channel/item">
<div class="item">
<h3>
<a href="{link}">
<xsl:value-of select="title">
</a>
</h3>
<hr/>
<span class="date">
Publication date : <xsl:value-of select="pubDate">
</span>
<br/>
<xsl:value-of select="description">
</div>
<span>
<a class="top" href="#top">Go to top</a>
</span>
</xsl:template>
</xsl:stylesheet>

That XSLT above will be used in the code using XslTransform.
RSS file will be loaded using XmlDocument class and XSLT using XSLTransform class; and do it some transform. Here is a quick sample of my code.

internal static string ReadXmlToHTML(string path, string xslpath)
{
StringBuilder strBuilder = new StringBuilder();
TextWriter strWriter = new StringWriter(strBuilder);

Uri uri = null;

if (Uri.TryCreate(path, UriKind.RelativeOrAbsolute, out uri))
{
Stream stream = null;
if (uri != null && uri.Scheme == Uri.UriSchemeHttp)
{
WebClient client = new WebClient();
byte[] datas = client.DownloadData(uri);
stream = new MemoryStream(datas);
}
if (stream != null)
{
XmlDocument document = new XmlDocument();
document.Load(stream);

XslTransform xslt = new XslTransform();
xslt.Load(HttpContext.Current.Server.MapPath(xslpath));
xslt.Transform(document, null, strWriter);
}
}
return strBuilder.ToString();
}


It will return a string that contain HTML that can be used in the ASP.NET

0 comments: