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

Subject: Re: [xsl] If vs. apply-templates for optional attributes
From: Jeni Tennison <jeni@xxxxxxxxxxxxxxxx>
Date: Fri, 7 Jun 2002 16:04:15 +0100
Hi Peter,

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

It looks as if you want to copy the attr attribute if it's there, and
not copy it if it isn't. If so, you should just do:

  <testelement>
    <xsl:copy-of select="@attr" />
    ...
  </testelement>

If the xsl:copy-of doesn't manage to find an attr attribute to copy,
then nothing gets added; if it does, then it adds the attribute.

For extensibility, to add a default attribute, I'd use the
apply-templates as you did in your second method, but keep the match
attribute of the template simple and use an xsl:choose inside:

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

and then:

<xsl:template match="*" mode="attr">
  <xsl:choose>
    <xsl:when test="@attr">
      <xsl:copy-of select="@attr" />
    </xsl:when>
    <xsl:otherwise>
      <xsl:attribute name="attr">default</xsl:attribute>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

(You could use a named template instead if you wanted; I'd use a
matching one if you were matching a subset of elements.)

Or, possibly, use an attribute set:

<xsl:attribute-set name="attr">
  <xsl:attribute name="attr">
    <xsl:choose>
      <xsl:when test="@attr"><xsl:value-of select="@attr" /></xsl:when>
      <xsl:otherwise>default</xsl:otherwise>
    </xsl:choose>
  </xsl:attribute>
</xsl:attribute-set>

with:

  <testelement xsl:use-attribute-sets="attr">
    ...
  </testelement>

but that isn't as controllable as a template (you can't change it so
that you *don't* add an attr attribute in some circumstances).

Cheers,

Jeni

---
Jeni Tennison
http://www.jenitennison.com/


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


Current Thread