Tal Zamirly
Tal Zamirly

Reputation: 117

Java: Converting RSS feed to HTML

I am currently doing a java project where I get a url which contains an RSS feed, and am required to convert that RSS feed into HTML. So I have done a bit of research and managed to convert it into XML, so I can convert it to HTML with XSLT. However, that process requires a XSL file, which I have no idea how to get/ create. How would I go about attempting this problem? I cannot hard code it, as the resource url may change the events/news on the site and therefore effect my output.

Upvotes: 1

Views: 2265

Answers (1)

MiMo
MiMo

Reputation: 11973

RSS feeds came in two formats: RSS 2.0 and ATOM - depending on which kind do you want/need to handle you'll need different XSLT.

This is a very simple XSLT that convert a RSS 2.0 feed into a HTML page:

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

  <xsl:output method="html" indent="yes"/>

  <xsl:template match="text()"></xsl:template>

  <xsl:template match="item">
    <h2>
      <a href="{link}">
        <xsl:value-of select="title"/>
      </a>
    </h2>
    <p>
      <xsl:value-of select="description" disable-output-escaping="yes"/>
    </p>
  </xsl:template>
  <xsl:template match="/rss/channel">
    <html>
      <head>
        <title>
          <xsl:value-of select="title"/>
        </title>
      </head>
    </html>
    <body>
      <h1>
        <a href="{link}">
          <xsl:value-of select="title"/>
        </a>
      </h1>
      <xsl:apply-templates/>
    </body>
  </xsl:template>

</xsl:stylesheet>

...and this is the same for a ATOM feed:

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

  <xsl:output method="html" indent="yes"/>

  <xsl:template match="text()"></xsl:template>

  <xsl:template match="atom:entry">
    <h2>
      <a href="{atom:link/@href}">
        <xsl:value-of select="atom:title"/>
      </a>
    </h2>
    <p>
      <xsl:value-of select="atom:summary"/>
    </p>
  </xsl:template>

  <xsl:template match="/atom:feed">
    <html>
      <head>
        <title>
          <xsl:value-of select="atom:title"/>
        </title>
      </head>
    </html>
    <body>
      <h1>
        <a href="{atom:link/@href}">
          <xsl:value-of select="atom:title"/>
        </a>
      </h1>
      <xsl:apply-templates/>
    </body>
  </xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions