Creating Generic Mapping Functions

Problem

You want to create reusable templates for performing operations on items in a node set.

Solution

The solution involves recursively processing the elements in $nodes and invoking the generic function, $func, on each element. You allow the possibility that the function specified by $func is parameterized. This parameter can be specified by $func-param. You further state that the default value of the $func-param is obtained from an attribute, @param1, in the generic functions tag. This stipulation allows the default to be a function of the specified generic:

<xsl:template name="generic:map"> <xsl:param name="nodes" select="/.."/> <xsl:param name="func" select=" 'identity' "/> <xsl:param name="func-param1" select="$generic:generics[self::generic:func and @name = $func]/@param1"/> <xsl:param name="i" select="1"/> <xsl:param name="result" select="/.."/> <xsl:choose> <xsl:when test="$nodes"> <xsl:variable name="temp"> <xsl:apply-templates select="$generic:generics[self::generic:func and @name = $func]"> <xsl:with-param name="x" select="$nodes[1]"/> <xsl:with-param name="i" select="$i"/> <xsl:with-param name="param1" select="$func-param1"/> </xsl:apply-templates> </xsl:variable> <xsl:call-template name="generic:map"> <xsl:with-param name="nodes" select="$nodes[position( ) > 1]"/> <xsl:with-param name="func" select="$func"/> <xsl:with-param name="func-param1" select="$func-param1"/> <xsl:with-param name="i" select="$i +1"/> <xsl:with-param name="result" ...

Get XSLT Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.