Recent Articles

Having Fun Transforming XML Feed with XSLT

If you operate DotNetNuke and use the News Feed module, you'll come across a thing called XSL or XSLT template. They essentially mean the same thing and stand for Extensible Stylesheet Language Transformations defined by W3C. What it does is take a plain XML and transform it into a human-readable document like HTML. Sounds wonderful?

I use RSS Feeds quite a bit. It's neat to pull interesting blogs or news feed into my site. Sometimes the RSS feed provided is too long or the default format is not as nice. So I decided to write my own XSLT template to transform the XML from the RSS feed. One of the issues I needed to deal with is reducing the number of news items to 10.

XSLT uses XQuery to locate data. XQuery is a query expression that you can use to select any arbitrary elements or attributes inside the XML easily. It also has some rudimental built-in functions that you can use to operate against the selected values such as substring().

<?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes"/> <xsl:param name="TITLE"/>
<xsl:template match="rss">
    <xsl:for-each select="channel/item">
        <xsl:if test="position() &lt; 10">
            <br /><strong><a href="{link}" target="_new"><xsl:value-of select="title"/></a></strong><br />
            <xsl:value-of disable-output-escaping="yes" select="description"/> <br />
        </xsl:if>
    </xsl:for-each>
</xsl:template>

<xsl:template match="description">
    <br><xsl:value-of select="."/> </br>
</xsl:template>
</xsl:stylesheet>

As you can see, the XSLT above looks a lot like XML mixed with some HTML tags. The HTML is the part I use to tell the template how to print out my XML data. You'll also notice the use of for-each to loop the elements found when I called the XQuery select expression that returned all elements belonging in nodes.

In order to limit the number of news items, I applied the if condition and test against the position value. It really looks like programming cocktailed into XML tags.

Personally, I find it hard to read but it works quite nicely for formatting XML documents. So I decided to show this to some tech savvy business people and see they think (these are the ones who call themselves Excel pros and knows to manipulate VB macros day in and out). Well, it's no surprise that they chocked at it when they saw the convoluted XSLT code.

You can learn up XQuery quickly from W3Schools and then read up on XSLT here.