Monday, February 02, 2009

Calling XSLT templates with predicates..

This is just a mental note for me, so hopefully I won't forget it in the future.

If you have an XSLT template that limits the result set with a predicate, you must call that template with the predicate intact. Here's an example:

Wrong:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="Items">
<xsl:apply-templates select="Item" />
</xsl:template>

<xsl:template match="Item[status='archived']">
<xsl:element name="title">
<xsl:value-of select="title" />
</xsl:element>
</xsl:template>

</xsl:stylesheet>


Right:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="Items">
<xsl:apply-templates select="Item[status='archived']" />
</xsl:template>

<xsl:template match="Item[status='archived']">
<xsl:element name="title">
<xsl:value-of select="title" />
</xsl:element>
</xsl:template>

</xsl:stylesheet>


I am ashamed at how long it took me to figure out what I was doing wrong. ;)

No comments: