XML technologies / XSLT / Reference: XSLT 1.0 and 2.0 elements / function
(Excerpt from “XSLT 2.0 & XPath 2.0” by Frank Bongers, chapter 6.)
A | B | C | D | E | F | G | H | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z
Top-level element xsl:function defines user functions available at runtime within template rules (stylesheet functions).
Classification | Declaration |
Function group | Defining stylesheet functions |
Introduced in | XSLT 2.0 |
Stylesheet position and permitted contents:
xsl:function occurs at the top level as a child of either xsl:stylesheet or xsl:transform.
A declaration of xsl:function may contain any number of xsl:param elements, one per supplied argument. A sequence constructor follows, mixing any number of XSLT instructions including extensions. After the last xsl:param element, optional xsl:message elements may be inserted for debugging or similar purposes.
Attributes:
Standard attributes apply. Declaration xsl:function also has three attributes: mandatory name and optional as and override.
as
Value | sequence-type |
Usage | Optional |
Introduced in | XSLT 2.0 |
Attribute as specifies the function’s return sequence type, so its value is a sequence-type expression.
If attribute as is set, function conversion rules (function conversion rules) convert the result to that type. (Note: See XPath 2.0 specification section 3.1.5 onward, Function conversion rules). Conversion failure is a type error (ERR XTTE0780). Without attribute as, the result remains unchanged.
name
Value | |
Usage | Mandatory |
Introduced in | XSLT 2.0 |
Mandatory attribute name names the function for calls. To avoid conflicts with system functions, its QName must have a prefix. An unprefixed name is a static error (ERR XTSE0740).
The prefix may bind to any namespace that is non-null. Reserved namespaces are forbidden, including XSLT, XML and various namespaces related to XML Schema. Violations are static errors (ERR XTSE0080).
override
Value | "yes" | "no" |
Usage | Optional |
Introduced in | XSLT 2.0 |
Attribute override takes "yes" or "no" to determine whether this function overrides a same-named processor-vendor function.
It defaults to "yes". The stylesheet function thus wins when attribute override is absent or explicitly set to "yes". All processors behave identically, ignoring any same-named vendor functions.
With value "no", an implemented same-named function takes precedence. This is useful when some processors may lack that extension: they use the stylesheet function as fallback, while the target platform uses its vendor implementation.
Purpose:
Top-level element xsl:function declares a stylesheet function: its name, parameters and their types, and implementation body. As a top-level declaration, it can access global variables and global parameters, which already exist. Tunnel parameters are inaccessible, as are local variables and parameters.
The function may be called in any XPath expression, including XPath patterns and their predicates in template rules.
A function cannot access its caller’s context. Its focus is undefined: the caller’s context item, position and size are unavailable. Caller-local variables are also unavailable, but their values can be passed as arguments.
Return sequences can be built freely. Instruction xsl:sequence is a simple choice for arbitrary sequences. Other sequence-returning instructions, such as xsl:perform-sort, or multi-instruction constructors also work. Attribute as of xsl:function can enforce a result datatype.
The name must be a QName whose namespace is in scope at declaration, preferably declared on root element xsl:stylesheet. To avoid copying that namespace to results, use attribute exclude-result-prefixes of xsl:stylesheet to exclude it.
Defining and assigning parameters:
Within declaration xsl:function, first define xsl:param elements matching argument count and order. The first argument maps to the first parameter, and so on.
<xsl:function name="meine:funktion">
<xsl:param name="param1"/>
<xsl:param name="param2"/>
...
</xsl:function>
is called with:
meine:funktion($wert_fuer_param1, $wert_fuer_param2)
Callers cannot assign by parameter name; names only reference values inside the function. Each parameter’s required type is specified on its xsl:param element using attribute as.
<xsl:function name="meine:funktion">
<xsl:param name="param1" as="xs:decimal" />
<xsl:param name="param2" as="xs:decimal" />
<!-- Werte addieren: -->
<xsl:sequence select="$param1 + $param2"/>
</xsl:function>
Subtypes are accepted without conversion. For example, xs:integer, a subtype of xs:decimal, retains its type. Otherwise conversion is attempted; only failure causes a runtime error (ERR XTTE0790). Without as, any supplied type is accepted.
Parameter definition requirements:
Optional parameters are forbidden: every declared parameter requires a value, even an empty sequence. Because passing values is mandatory (mandatory), no default may be declared. Element xsl:param must be empty and its attribute select is forbidden, as with all mandatory parameters.
Attribute required of xsl:param is forbidden for function parameters. Attribute tunnel is forbidden too, since functions cannot read tunnel values, again for context reasons.
A valid function declaration adds it to the static context, callable throughout the stylesheet, unless a same-named higher-import-precedence function exists or, with override="no", a same-named extension exists.
Identifying functions by arity:
Functions are identified by name and argument count (arity). These rules apply only to equal argument counts. Same-named functions of different arities coexist:
<!-- Funktion 1 mit zwei Argumenten: -->
<xsl:function name="kein:problem">
<xsl:param name="param1" as="xs:decimal" />
<xsl:param name="param2" as="xs:decimal" />
<!-- Werte addieren: -->
<xsl:sequence select="$param1 + $param2"/>
</xsl:function>
<!-- Funktion 2 mit drei Argumenten: -->
<xsl:function name="kein:problem">
<xsl:param name="param1" as="xs:decimal" />
<xsl:param name="param2" as="xs:decimal" />
<xsl:param name="param3" as="xs:decimal" />
<!-- Werte addieren: -->
<xsl:sequence select="$param1 + $param2 + $param3"/>
</xsl:function>
Calls distinguish both functions by argument count:
kein:problem($p1, $p2) <!-- Aufruf Funktion 1 -->
kein:problem($p1, $p2, $p3) <!-- Aufruf Funktion 2 -->
No polymorphism:
Types are checked when parameters enter the function, not when selecting the call, so overloads cannot differ only in argument types: no polymorphism. Two same-named functions with equal arity are a static error (ERR XTSE0770), but only at equal import precedence and without a higher-precedence function of that signature. Beware of module inclusion with xsl:include.
Examples:
Example 1 – Convert a number to Roman numerals:
<xsl:function name="bsp:roemisch">
<xsl:param name="eingabezahl" as="xs:integer"/>
<xsl:variable name="roemische-zahl">
<xsl:number value="$eingabezahl" format="I"/>
</xsl:variable>
<xsl:sequence select="$roemische-zahl" as="xs:string"/>
</xsl:function>
This function converts an integer of type xs:integer to Roman numerals returned as a string. A template rule might call it like this:
...
<xsl:value-of select="bsp:roemisch(@baujahr)"/>
...
Attribute baujahr should contain a year. For baujahr="1850" it returns “MDCCCL”. Conversion uses xsl:number with uppercase Roman formatting format="I". Its return value must first be stored in a variable rather than used directly.
<xsl:variable name="roemische-zahl">
<xsl:number value="$eingabezahl" format="I"/>
</xsl:variable>
Attribute select of xsl:sequence references that variable to return the result to the call site:
<xsl:sequence select="$roemische-zahl" as="xs:string"/>
Attribute as forces a string result, though xsl:number already produces strings. Without attribute as, no conversion occurs.
Example 2 – Reverse word order in a sentence:
This function reverses a sentence’s word order. The sentence is static here but could be a global parameter.
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:bsp="http://beispiel.com/namespace" exclude-result-prefixes="bsp">
<xsl:function name="bsp:umkehren">
<xsl:param name="satz" as="xs:string"/>
<xsl:sequence select="if (contains($satz, ' ')) then concat(bsp:umkehren(substring-after($satz, ' ')),' ', substring-before($satz, ' ')) else $satz" as="xs:string"/>
</xsl:function>
<xsl:template match="/">
<ausgabe>
<xsl:value-of select="bsp:umkehren('Eins Zwei Drei Vier')"/>
</ausgabe>
</xsl:template>
</xsl:stylesheet>
The stylesheet outputs:
<ausgabe>Vier Drei Zwei Eins</ausgabe>
Its namespace is declared on the stylesheet element and excluded from result copying:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:bsp="http://beispiel.com/namespace"
exclude-result-prefixes="bsp">
The sentence is a parameter; actual work happens in attribute select of xsl:sequence. XPath 2.0 permits IF-ELSE conditions in expressions. The if test checks for a space and therefore separate words. Without one, else returns input directly:
select="if (contains($satz, ' ')) then ... else $satz"
The interesting branch is then, taken when spaces exist. The function calls itself recursively:
then concat(bsp:umkehren(substring-after($satz, ' ')),' ', substring-before($satz,' '))
Recursion continues while the substring-after() part, shortened by its first word each time, still contains a space. Otherwise branch else stops recursion. Attribute select of xsl:sequence holds the reversed sentence and returns it to the call site.
Example 3 – Enclose a string in parentheses:
Stylesheet:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fb="http://www.webdimensions.de/func" exclude-result-prefixes="fb">
<xsl:function name="fb:einklammern">
<xsl:param name="eingabe"/>
<xsl:sequence select="concat('(',$eingabe,')')"/>
</xsl:function>
<xsl:template name="einklammern">
<ergebnis>
<xsl:value-of select="fb:einklammern('Beispiel')"/>
</ergebnis>
</xsl:template>
...
Result:
<ergebnis>(Beispiel)</ergebnis>Concatenating parentheses occurs entirely in the XPath expression of attribute select of xsl:sequence. The function is called from xsl:value-of, which writes the value to the result. (Note: A named template could do the same in XSLT 1.0.)
Example 4 – Calculate a factorial:
Stylesheet:
<xsl:function name="fb:fakultaet">
<xsl:param name="zahl" type="xsd:integer"/>
<xsl:sequence select="if($zahl=1) then 1 else $zahl * fb:fakultaet($zahl – 1)"/>
</xsl:function>
The function computes its argument’s factorial. In the XPath expression of attribute select of xsl:sequence, it calls itself recursively. This is legal because functions may be called in any XPath expression, including within themselves.
Element definition:
XSLT 1.0:
Element unavailable in XSLT 1.0.
XSLT 2.0:
<!-- Category: declaration -->
<xsl:function
name = qname
as? = sequence-type
override? = "yes" | "no">
<!-- Content: (xsl:param*, sequence-constructor) -->
</xsl:function>
Copyright © Galileo Press, Bonn 2008
You may print the online version for your private use.
Otherwise, this chapter from “XSLT 2.0 & XPath 2.0 ― Das umfassende Handbuch” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
Galileo Press, Rheinwerkallee 4, 53227 Bonn