use-when

Inasmuch as use-when is one of the standard attributes in XSLT 2.0 (and later) rather than being on a particular XSLT element, it seldom gets much of a mention; e.g., currently only 568 mentions on the XSL-List according to MarkMail (and some of those are false positives).

use-when (and xsl:use-when on non-XSLT elements) is for “conditional element inclusion” and is very useful for excluding elements that either aren’t currently useful or that will cause errors if acted upon. The use-when in the example below causes the xsl:value-of to be used only when saxon:line-number() is available, thereby avoiding the Saxon extension functions are not available under Saxon-HE message from more recent versions of Saxon HE where saxon:line-number() is no longer available but producing a useful result on older Saxon HE versions where the function is available.

<!-- Leftover intermediate elements. -->
<xsl:template match="t:*">
  <xsl:if test="$debug">
    <xsl:message>
      <xsl:value-of select="t:node-basename(.)" />
      <xsl:value-of
        use-when="function-available('saxon:line-number')"
        select="concat(':', saxon:line-number())"
        xmlns:saxon="http://saxon.sf.net/" />
      <xsl:text> :: </xsl:text>
      <xsl:copy-of select="." />
    </xsl:message>
  </xsl:if>
  <xsl:apply-templates />
</xsl:template>

The use-when expression is evaluated very early in the processing of the stylesheet, and you can’t use variable references in the expression. So don’t be tempted to try:

<xsl:message use-when="$debug">
...
</xsl:message>