Re: [xsl] Using keys in templates

Subject: Re: [xsl] Using keys in templates
From: "M. David Peterson" <m.david@xxxxxxxxxx>
Date: Tue, 13 Jul 2004 09:23:02 -0600
Jeni Tennison wrote:


<xsl:template match="module"> <xsl:apply-templates select="dist[generate-id(.) = generate-id(key('dists', @name))]" /> </xsl:template>

<xsl:template match="dist">
  <!-- this template only processed for the first dist element with
       each particular name -->
  ...
</xsl:template>


The other benefit that comes with Jeni's approach is the ability to use variables within the value of the select attribute of <xsl:apply-templates...>, something that is not legal in the match attribute of <xsl:template...>. As Jeni pointed out...


"Locating which template to use to process a node takes time, so you
should try to apply templates to as small a set as possible rather
than trying to find a template for every node, but only doing
something with some of them."

... this method ensures that only those elements which evaluate to true are sent to be matched to a template. In your original post you were using the value of a variable as the value for the key function to match against the list of elements selected using <xsl:key...>. As both Jeni and David indirectly pointed out the creation of the "dist" variable wasn't necessary in your particular case as the dist element was still the context element when you used the conditional <xsl:if...> element and as such "@name" referenced the same value that was being held in the "dist" variable. But if this wasnt the case (you had implemented a for-each loop for example) then using the value of this variable within the key function would have made sense and would have allowed you the ability to further qualify what elements should be selected and matched to a template.

Hope you find this helpful!

Best regards,

<M:D/>

Current Thread