RE: [xsl] If vs. apply-templates for optional attributes

Subject: RE: [xsl] If vs. apply-templates for optional attributes
From: "Dunning, John" <JDunning@xxxxxxxxx>
Date: Fri, 7 Jun 2002 10:57:16 -0400
If you're going to be using this type of test frequently (I'm not sure
whether you meant for the same element a dozen times or for a dozen
elements), you could use a named template with a parameter:

<xsl:template match="testelement">
	<xsl:call-template name="attTest">
	  <xsl:with-param name="node" select="."/>
	</xsl:call-template>
</xsl:template>

<xsl:template name="attTest">
<xsl:param name="node"/>
<xsl:copy>
	<xsl:if test="not($node[@attr])">
		<xsl:attribute name="attr">test</xsl:attribute>
	</xsl:if>
</xsl:copy>
</xsl:template>	

HTH,
John

-----Original Message-----
From: Hunsberger, Peter [mailto:Peter.Hunsberger@xxxxxxxxxx]
Sent: Friday, June 07, 2002 10:32 AM
To: 'xsl-list@xxxxxxxxxxxxxxxxxxxxxx'
Subject: [xsl] If vs. apply-templates for optional attributes


Any opinions on which of the following two ways of adding an optional
attribute to an element is more efficient?

Method 1 - If:

  <testelement>>
      <xsl:if test="@attr != ''">
         <xsl:attribute name="attr"><xsl:value-of
select="@attr"/></xsl:attribute>
      </xsl:if>
  </testelement>

Method 2 - Apply templates:

  <testelement>>
      <xsl:apply-templates mode="attr" select="."/>
  </testelement>

  <xsl:template match="*[@attr]" mode="attr">
     <xsl:attribute name="attr"><xsl:value-of
select="@attr"/></xsl:attribute>
  </xsl:template>

I have about a dozen spots where I need to do this type of test, so using
method 2 ends up reducing the size of the XSLT overall.  Also, method 2 can
easily be extended, in particular to provide a default value by adding a
template like:

  <xsl:template match="*[not(@attr)]" mode="attr">
     <xsl:attribute name="attr">default</xsl:attribute>
  </xsl:template>

where as method 1 has to be converted into a choose block.  As a result I've
been favoring method 2.  However, I thought I should make a sanity check on
whether it might have  performance implications? It seems to me that method
2 has to be somewhat less efficient, but perhaps not enough to matter? 

I'll note that one might have to be a little careful on what you push to the
modal templates in method 2 (worse case is to add a default template to
gobble up anything not wanted), and that might add other performance issues,
but in my case that's not an issue...

Peter Hunsberger

Phone: 901-495-5252
E-mail: Peter.Hunsberger@xxxxxxxxxx


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list

 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list


Current Thread