Sponsored

XSLT Reference

apply()

XSLT 3.0 higher-order function

Calls a function item with arguments supplied as an array, enabling dynamic dispatch with a variable argument list.

Syntax
apply(function, array-of-args)

Description

apply() invokes a function item, passing its arguments as members of an array. This enables dynamic function calls where both the function and its argument list are determined at runtime. The number of array members must match the arity of the function, otherwise a type error is raised.

Parameters

ParameterTypeRequiredDescription
functionfunction(*)YesThe function item to invoke.
array-of-argsarray(*)YesAn array whose members are the arguments to pass. Member count must equal the function arity.

Return value

item()* — the result returned by the invoked function.

Examples

Dynamic dispatch with apply()

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  xmlns:f="http://example.com/functions">

  <xsl:output method="xml" indent="yes"/>

  <xsl:function name="f:add" as="xs:integer">
    <xsl:param name="a" as="xs:integer"/>
    <xsl:param name="b" as="xs:integer"/>
    <xsl:sequence select="$a + $b"/>
  </xsl:function>

  <xsl:template match="/">
    <result>
      <!-- Call f:add with arguments [3, 7] supplied as an array -->
      <xsl:variable name="fn" select="f:add#2"/>
      <xsl:variable name="args" select="[3, 7]"/>
      <value><xsl:value-of select="apply($fn, $args)"/></value>
    </result>
  </xsl:template>
</xsl:stylesheet>

Output:

<result>
  <value>10</value>
</result>

Applying a selected operation dynamically

Input XML:

<?xml version="1.0" encoding="UTF-8"?>
<operations>
  <op name="upper" value="hello"/>
  <op name="lower" value="WORLD"/>
</operations>

Stylesheet:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="3.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/operations">
    <results>
      <xsl:for-each select="op">
        <xsl:variable name="fn" select="
          if (@name = 'upper') then upper-case#1
          else lower-case#1"/>
        <result><xsl:value-of select="apply($fn, [string(@value)])"/></result>
      </xsl:for-each>
    </results>
  </xsl:template>
</xsl:stylesheet>

Output:

<results>
  <result>HELLO</result>
  <result>world</result>
</results>

Notes

  • apply() is defined in XPath 3.0 / XSLT 3.0. It is not available in XSLT 2.0 or earlier.
  • The function arity must exactly match the number of members in the array; a mismatch causes err:FOAP0001.
  • apply() is the complement of inline function items and partial function application.
  • Useful for implementing dispatch tables and strategy patterns in XSLT.

See also