XSLT Example

Parsing XML with XSLT

Just a little something to see how I can use XSLT to create a list of items from an XML document. The XML came from DeviantArt, and since it was using RSS syntax, I had to change it a little bit because it was using stuff like <media:content>, which I just switched to <mediacontent>.

I like to use variables to build out items like this which contain a link and various other attributes that are all pulling their values from XML.

View it in action

Here's the XSLT used to create the list

<h1><xsl:value-of select="/channel/title"/></h1>
<ul class="itemList thumbs">
	<xsl:for-each select="/channel/item">
		<xsl:variable name="src" select="mediathumbnail/@url"/>
		<xsl:variable name="alt" select="title"/>
		<xsl:variable name="link" select="mediacontent/@url"/>
		<xsl:variable name="desc">
			<xsl:value-of select="mediadescription" disable-output-escaping="yes"/>
		</xsl:variable>
		<xsl:variable name="date" select="pubDate"/>
		<xsl:variable name="category" select="mediacategory/@label"/>
		<xsl:variable name="lbTitle">
			<xsl:value-of select="$category"/> — <xsl:value-of select="$date"/> —<xsl:value-of select="$desc"/>
		</xsl:variable>		
		<xsl:variable name="className">
			<xsl:choose>
				<xsl:when test="position() = last()">
					last clearfix
				</xsl:when>
				<xsl:otherwise>
					clearfix
				</xsl:otherwise>
			</xsl:choose>
		</xsl:variable>
		<li class="{$className}">
			<a class="floatLeft" href="{$link}" rel="lightbox-myGroup" lightboxtitle="{$lbTitle}">
				<img src="{$src}" alt="{$alt}" width="200"/>
			</a>
			<div>
				<h4><strong><xsl:value-of select="$alt"/></strong></h4>
				<p><em><xsl:value-of select="$category"/></em><br/><xsl:value-of select="$date"/></p>
				<p><xsl:value-of select="$desc"/></p>
				<p>Click on the image to see it larger</p>
			</div>
		</li>
	</xsl:for-each>
</ul>