XSL: Detect first-of-type element in a list

Sometimes you want your XSL transformation to process first element of a type in a child list in different manner. For example, using the following data ...
<?xml version="1.0" encoding="UTF-8" ?>
<list>
<author>John Brown</author>
<author>Jim Small</author>
<editor>Jane Doe</editor>
<editor>Grace Kelly</editor>
</list>
... you might want to process the first editor in a slightly different manner. There are two simple solutions:

(A) Write two transformation rules, one for the first element, one for the remaining ones:
<xsl:template match="editor[1]">
<!-- transform the first editor in list -->
</xsl:template>

<xsl:template match="editor">
<!-- transform the remaining editor elements -->
</xsl:template>
(B) Use preceding-sibling axis to check whether an element is the first of its type:
<xsl:template match="editor">
<xsl:if test="not(preceding-sibling::editor)">Editors:</xsl:if>
<xsl:value-of select="text()" /> (<xsl:value-of select="position()" />)
</xsl:template>
You should use the first method when the handling of the first element is radically different from the rest and the second one when you only need to set a few attributes or write a lead-in text.

No comments:

Post a Comment