Tuesday, July 04, 2006

RSS XML Stylesheet Example

Some time ago I was working for a client who required their CMS system to output particular items as RSS feeds. The CMS output XML and used XSLT to tranform to HTML. This provided a very handy mechanism indeed for conversion to RSS.

 

My final solution used a stylesheet to simply take the XML from the CMS and convert it to an RSS 2.0 format feed rather than HTML! Below I have rewritten the stylesheet (adding a few flourishes) which should be easily adaptable and fairly generic for this type of conversion as long as the XML provides the following attributes in a fairly sensible format!

 

XML Needs to contain the following items for the feed:

    TITLE OF FEED

    LINK TO FEED HOMEPAGE

    DESCRIPTION OF FEED

    COPYRIGHT NOTICE

 

XML Needs to contain the following items for EACH ARTICLE:

    TITLE OF ARTICLE

    LINK TO ARTICLE

    DESCRIPTION OF ARTICLE

    CREATOR OF ARTICLE

    DATE OF ARTICLE

 

An eaxmple of how the XML might look is (it might not look at all like this in which case I might advise a pre-RSS xml conversion with XSL to bring it into line with the below and separate the XML conversion code form the XML-RSS code):

 

<data>

  <feed title="" link="description="" copyright="">

    <item>

     <title></title>

     <link></link>

     <description></description>

     <creator></creator>

     <date></date>

    </item>

    <item>

     <title></title>

     <link></link>

     <description></description>

     <creator></creator>

     <date></date>

    </item>

    <item>

     <title></title>

     <link></link>

     <description></description>

     <creator></creator>

     <date></date>

    </item>

  </feed>

</data>

 

And finally the actual stylesheet - obviously this could easily be extended to manage multiple feed xml but if I did it all here it'd take the fun out of it!

 

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

<xsl:output method="xml" indent="no" encoding="unicode" omit-xml-declaration="yes" media-type="text/xml"/>

 

<xsl:template match="data">

<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">

<channel>

  <title>TITLE OF FEED</title>

  <link>LINK TO FEED HOMEPAGE</link>

  <description>DESCRIPTION OF FEED</description>

  <language>en-gb</language>

  <dc:rights>COPYRIGHT NOTICE</dc:rights>

  <xsl:for-each select="ITEMNODESET">

  <item>

      <title>TITLE OF ARTICLE</title>

      <link>LINK TO ARTICLE</link>

      <description>DESCRIPTION OF ARTICLE</description>

      <dc:creator>CREATOR OF ARTICLE</dc:creator>

      <dc:date>DATE OF ARTICLE</dc:date>   

  </item>

  </xsl:for-each>

</channel>

</rss>           

</xsl:template>

</xsl:stylesheet>

 

 

No comments: