If the effective value of the
collation
attribute of xsl:sort
is a relative
URI, then it is resolved against the base URI of the
xsl:sort
element.
[ERR XTDE1035] It is a non-recoverable dynamic
error if the collation
attribute of
xsl:sort
(after
resolving against the base URI) is not a URI that is
recognized by the implementation as referring to a
collation.
Note:
It is entirely for the implementation to determine whether it recognizes a particular collation URI. For example, if the implementation allows collation URIs to contain parameters in the query part of the URI, it is the implementation that determines whether a URI containing an unknown or invalid parameter is or is not a recognized collation URI. The fact that this error is described as non-recoverable thus does not prevent an implementation applying a fallback collation if it chooses to do so.
The lang
and case-order
attributes are ignored if a collation
attribute is present. But in the absence of a
collation
attribute, these attributes
provide input to an implementation-defined
algorithm to locate a suitable
collation:
The lang
attribute indicates that a
collation suitable for a particular natural language
should be used. The
effective value of the
attribute must be a value
that would be valid for the xml:lang
attribute (see [XML 1.0]).
The case-order
attribute indicates
whether the desired collation should sort upper-case letters before
lower-case or vice versa. The effective value of the
attribute must be either
lower-first
(indicating that lower-case
letters precede upper-case letters in the collating
sequence) or upper-first
(indicating
that upper-case letters precede lower-case).
If none of the collation
,
lang
or case-order
attributes
is present, the collation is chosen in an implementation-defined
way. It is not required that
the default collation for sorting should be the same as
the default collation used when
evaluating XPath expressions, as described in 5.4.1 Initializing the Static
Context and 3.6.1 The
default-collation attribute.
Note:
It is usually appropriate, when sorting, to use a strong collation, that is, one that takes account of secondary differences (accents) and tertiary differences (case) between strings that are otherwise equal. A weak collation, which ignores such differences, may be more suitable when comparing strings for equality.
Useful background information on international
sorting is provided in [UNICODE
TR10]. The case-order
attribute may be
interpreted as described in section 6.6 of [UNICODE TR10].

<xsl:perform-sort
select? = expression>

</xsl:perform-sort>
The xsl:perform-sort
instruction is used to return a sorted sequence.
The initial sequence is obtained
either by evaluating the select
attribute or
by evaluating the contained sequence constructor (but not
both). If there is no select
attribute and no
sequence constructor then the initial sequence (and
therefore, the sorted sequence) is an empty
sequence.
[ERR XTSE1040] It is a static error if
an xsl:perform-sort
instruction with a select
attribute has any
content other than xsl:sort
and xsl:fallback
instructions.
The result of the xsl:perform-sort
instruction is the result of sorting its initial
sequence using its contained sort key
specification.
The following stylesheet function sorts a sequence of atomic values using the value itself as the sort key.
<xsl:function name="local:sort" as="xs:anyAtomicType*"> <xsl:param name="in" as="xs:anyAtomicType*"/> <xsl:perform-sort select="$in"> <xsl:sort select="."/> </xsl:perform-sort> </xsl:function>
The following example defines a function that sorts books by price, and uses this function to output the five books that have the lowest prices:
<xsl:function name="bib:books-by-price" as="schema-element(bib:book)*"> <xsl:param name="in" as="schema-element(bib:book)*"/> <xsl:perform-sort select="$in"> <xsl:sort select="xs:decimal(bib:price)"/> </xsl:perform-sort> </xsl:function> ... <xsl:copy-of select="bib:books-by-price(//bib:book)[position() = 1 to 5]"/>
When used within xsl:for-each
or
xsl:apply-templates
,
a sort key specification
indicates that the sequence of items selected by that
instruction is to be processed in sorted order, not in the
order of the supplied sequence.
For example, suppose an employee database has the form
<employees> <employee> <name> <given>James</given> <family>Clark</family> </name> ... </employee> </employees>
Then a list of employees sorted by name could be generated using:
<xsl:template match="employees">
 <xsl:apply-templates select="employee"> <xsl:sort select="name/family"/> <xsl:sort select="name/given"/> </xsl:apply-templates>
 </xsl:template> <xsl:template match="employee">
 <xsl:value-of select="name/given"/> <xsl:text> </xsl:text> <xsl:value-of select="name/family"/>
 </xsl:template>
When used within xsl:for-each-group
,
a sort key specification
indicates the order in which the groups are to be
processed. For the effect of xsl:for-each-group
,
see 14 Grouping.
The facilities described in this section are designed to allow items in a sequence to be grouped based on common values; for example it allows grouping of elements having the same value for a particular attribute, or elements with the same name, or elements with common values for any other expression. Since grouping identifies items with duplicate values, the same facilities also allow selection of the distinct values in a sequence of items, that is, the elimination of duplicates.
Note:
Simple elimination of duplicates can also be achieved
using the function
distinct-values
FO
in the core function library: see [Functions and Operators].
In addition these facilities allow grouping based on
sequential position, for example selecting groups of adjacent
para
elements. The facilities also provide an
easy way to do fixed-size grouping, for example identifying
groups of three adjacent nodes, which is useful when
arranging data in multiple columns.
For each group of items identified, it is possible to evaluate a sequence constructor for the group. Grouping is nestable to multiple levels so that groups of distinct items can be identified, then from among the distinct groups selected, further sub-grouping of distinct items in the current group can be done.
It is also possible for one item to participate in more than one group.
current-group
() as
item()*
[Definition: The evaluation context for XPath
expressions
includes a component called the current
group, which is a sequence. The current group is the
collection of related items that are processed collectively
in one iteration of the xsl:for-each-group
element.]
While an xsl:for-each-group
instruction is being evaluated, the current group
will be non-empty. At other times, it will be an empty
sequence.
The function current-group
returns the current group.
The function takes no arguments.
[ERR XTSE1060] It is a static error if
the current-group
function is used within a pattern.
current-grouping-key
() as
xs:anyAtomicType?
[Definition: The evaluation context for XPath expressions includes a component called the current grouping key, which is an atomic value. The current grouping key is the grouping key shared in common by all the items within the current group.]
While an xsl:for-each-group
instruction with a group-by
or
group-adjacent
attribute is being evaluated,
the current grouping key will be
a single atomic value. At other times, it will
be the empty sequence.
The function current-grouping-key
returns the current grouping key.
Although the grouping keys of all items in a
group are by definition equal, they are not necessarily
identical. For example, one might be an
xs:float
while another is an
xs:decimal
. The current-grouping-key
function is defined to return the grouping key of the
initial
item in the group, after atomization and casting of
xs:untypedAtomic
to
xs:string
.
The function takes no arguments.
[ERR XTSE1070] It is a static error if
the current-grouping-key
function is used within a pattern.
xsl:for-each-group
Element
<xsl:for-each-group
select = expression
group-by? = expression
group-adjacent? = expression
group-starting-with? = pattern
group-ending-with? = pattern
collation? = { uri }>

</xsl:for-each-group>
This element is an instruction that may be used anywhere within a sequence constructor.
[Definition: The xsl:for-each-group
instruction allocates the items in an input
sequence into groups of items (that is, it
establishes a collection of sequences) based either on
common values of a grouping key, or on a pattern that the initial or final
node in a group must match.] The sequence constructor
that forms the content of the xsl:for-each-group
instruction is evaluated once for each of these groups.
[Definition: The sequence of items to be grouped, which
is referred to as the population, is determined by
evaluating the XPath expression contained in the
select
attribute.]
[Definition: The population is treated as a sequence; the order of items in this sequence is referred to as population order].
A group is never empty. If the population is empty, the
number of groups will be zero. The assignment of items to
groups depends on the group-by
,
group-adjacent
,
group-starting-with
, and
group-ending-with
attributes.
[ERR XTSE1080] These four attributes are mutually exclusive: it is a static error if none of these four attributes is present, or if more than one of them is present.
[ERR XTSE1090] It is an error to specify
the collation
attribute if neither the
group-by
attribute nor
group-adjacent
attribute is specified.
[Definition: If either of the group-by
attribute or group-adjacent
attributes is
present, then grouping keys are calculated for each
item in the population. The grouping keys
are the items in the sequence obtained by evaluating the
expression contained in the group-by
attribute
or group-adjacent
attribute, atomizing the
result, and then casting an xs:untypedAtomic
value to xs:string
.]
When calculating grouping keys for an item in the
population, the expression contained in the
group-by
or group-adjacent
attribute is evaluated with that item as the context item,
with its position in population order as the
context position, and with the
size of the population as the context size. The resulting sequence
is atomized,
and each atomic value in the atomized sequence acts as a
grouping
key for that item in the population.
If the group-by
attribute is present, then
an item in the population may have multiple grouping keys:
that is, the group-by
expression evaluates to
a sequence. The item is included in as many groups as there
are distinct grouping keys (which may be zero). If the
group-adjacent
attribute is used, then each
item in the population must have
exactly one grouping key value.
[ERR XTTE1100] It is a type error if the
grouping key evaluated using the
group-adjacent
attribute is an empty sequence,
or a sequence containing more than one item.
Grouping
keys are compared using the rules for the
eq
operator appropriate to their dynamic type.
Values of type xs:untypedAtomic
are cast to xs:string
before the comparison.
Two items that are not comparable using the eq
operator are considered to be not equal, that is, they are
allocated to different groups. If the values are strings,
or untyped atomic values, then if there is a
collation
attribute the values are compared
using the collation specified as the effective
value of the collation
attribute, resolved
if relative against the base URI of the xsl:for-each-group
element. If there is no collation
attribute
then the default collation is
used.
For the purposes of grouping, the value NaN
is considered equal to itself.
[ERR XTDE1110] It is a non-recoverable dynamic
error if the collation URI specified to xsl:for-each-group
(after resolving against the base URI) is a
collation that is not recognized by the implementation.
(For notes, [see ERR XTDE1035].)
For more information on collations, see 13.1.3 Sorting Using Collations.
[ERR XTTE1120] When the
group-starting-with
or
group-ending-with
attribute is used, it is a
type error
if the result of evaluating the select
expression contains an item that is not a node.
If the group-by
attribute is present,
the items in the population are examined, in
population order. For each item J, the
expression in the group-by
attribute is
evaluated to produce a sequence of zero or more
grouping key values. For each
one of these grouping keys, if there is
already a group created to hold items having that
grouping key value, J is added to that
group; otherwise a new group is created for items with
that grouping key value, and J becomes its
first member.
An item in the population may thus be assigned to zero, one, or many groups. An item will never be assigned more than once to the same group; if two or more grouping keys for the same item are equal, then the duplicates are ignored. An item here means the item at a particular position within the population—if the population contains the same node at several different positions in the sequence then a group may indeed contain duplicate nodes.
The number of groups will be the same as the number of distinct grouping key values present in the population.
If the group-adjacent
attribute is
present, the items in the population are examined, in
population order. If an item has the same value for the
grouping key as its preceding
item within the population (in population order), then it
is assigned to the same group as its preceding item;
otherwise a new group is created and the item becomes
its first member.
If the group-starting-with
attribute is
present, then its value must
be a pattern. In this case,
the items in the population must all be nodes.
The nodes in the population are examined in population order. If a node matches the pattern, or is the first node in the population, then a new group is created and the node becomes its first member. Otherwise, the node is assigned to the same group as its preceding node within the population.
If the group-ending-with
attribute is
present, then its value must
be a pattern. In this case,
the items in the population must all be nodes.
The nodes in the population are examined in population order. If a node is the first node in the population, or if the previous node in the population matches the pattern, then a new group is created and the node becomes its first member. Otherwise, the node is assigned to the same group as its preceding node within the population.
[Definition: For each group, the item within the group that is first in population order is known as the initial item of the group.]
[Definition: There is an ordering among
groups referred to as
the order of first appearance. A group G
is defined to precede a group H in order of
first appearance if the initial item of G
precedes the initial item of H in population
order. If two groups G and H
have the same initial item (because the item is in both
groups) then G precedes H if the
grouping
key of G precedes the grouping key of
H in the sequence that results from evaluating
the group-by
expression of this initial
item.]
[Definition: There is another ordering among
groups referred to as processing order. If
group R precedes group S in
processing order, then in the result sequence returned by
the xsl:for-each-group
instruction the items generated by processing group
R will precede the items generated by processing
group S.]
If there are no xsl:sort
elements
immediately within the xsl:for-each-group
element, the processing order of the
groups is the
order of first appearance.
Otherwise, the xsl:sort
elements
immediately within the xsl:for-each-group
element define the processing order of the groups (see 13
Sorting). They do not affect the order of items
within each group. Multiple sort key components are
allowed, and are evaluated in major-to-minor order. If two
groups have the same values for all their sort key
components, they are processed in order of first
appearance.
The select
expression of an xsl:sort
element is
evaluated once for each group. During this evaluation, the
context
item is the initial item of the group, the
context position is the position
of this item within the set of initial items (that is, one
item for each group in the population) in population
order, the context size is the number of
groups, the current group is the group whose
sort
key value is being determined, and the current grouping key is the
grouping key for that group. If the xsl:for-each-group
instruction uses the group-starting-with
or
group-ending-with
attributes, then the current
grouping key is the empty sequence.
For example, this means that if the grouping key
is @category
, you can sort the groups in
order of their grouping key by writing <xsl:sort
select="current-grouping-key()"/>
; or you can
sort the groups in order of size by writing
<xsl:sort
select="count(current-group())"/>
The sequence constructor
contained in the xsl:for-each-group
element is evaluated once for each of the groups, in processing order. The
sequences that result are concatenated, in processing
order, to form the result of the xsl:for-each-group
element. Within the sequence constructor, the
context
item is the initial item of the relevant group,
the context position is the position
of this item among the sequence of initial items (one item
for each group) arranged in processing order of the
groups, the context size is the number of
groups, the current group is the group being processed,
and the current grouping key is the
grouping key for that group. If the xsl:for-each-group
instruction uses the group-starting-with
or
group-ending-with
attributes, then the current
grouping key is the empty sequence. This has the
effect that within the sequence constructor, a
call on position()
takes successive values
1, 2, ... last()
.
During the evaluation of a stylesheet function, the current group and current grouping key are set to the empty sequence, and revert to their previous values on completion of evaluation of the stylesheet function.
On completion of the evaluation of the xsl:for-each-group
instruction, the current group and current grouping key
revert to their previous value.
The following example groups a list of nodes based on common values. The resulting groups are numbered but unsorted, and a total is calculated for each group.
Source XML document:
<cities> <city name="Milano" country="Italia" pop="5"/> <city name="Paris" country="France" pop="7"/> <city name="München" country="Deutschland" pop="4"/> <city name="Lyon" country="France" pop="2"/> <city name="Venezia" country="Italia" pop="1"/> </cities>
More specifically, the aim is to produce a four-column
table, containing one row for each distinct country. The
four columns are to contain first, a sequence number
giving the number of the row; second, the name of the
country, third, a comma-separated alphabetical list of
the city names within that country, and fourth, the sum
of the pop
attribute for the cities in that
country.
Desired output:

 Position	 Country	 List of Cities	 Population

 1	 Italia	 Milano, Venezia	 6

 2	 France	 Lyon, Paris	 9

 3	 Deutschland	 München	 4

Solution:

 Position	 Country	 City List	 Population
 <xsl:for-each-group select="cities/city" group-by="@country">
 <xsl:value-of select="position()"/>	 <xsl:value-of select="@country"/>	  <xsl:value-of select="current-group()/@name" separator=", "/> 	 <xsl:value-of select="sum(current-group()/@pop)"/>
 </xsl:for-each-group>

Sometimes it is necessary to use a composite grouping key: for example, suppose the source document is similar to the one used in the previous examples, but allows multiple entries for the same country and city, such as:
<cities> <city name="Milano" country="Italia" year="1950" pop="5.23"/> <city name="Milano" country="Italia" year="1960" pop="5.29"/> <city name="Padova" country="Italia" year="1950" pop="0.69"/> <city name="Padova" country="Italia" year="1960" pop="0.93"/> <city name="Paris" country="France" year="1951" pop="7.2"/> <city name="Paris" country="France" year="1961" pop="7.6"/> </cities>
Now suppose we want to list the average value of
@pop
for each (country, name) combination.
One way to handle this is to concatenate the parts of the
key, for example <xsl:for-each-group
select="concat(@country, '/', @name)">
. A more
flexible solution is to nest one xsl:for-each-group
element directly inside another:
<xsl:for-each-group select="cities/city" group-by="@country"> <xsl:for-each-group select="current-group()" group-by="@name">
<xsl:value-of select="@name"/>, <xsl:value-of select="@country"/>: <xsl:value-of select="avg(current-group()/@pop)"/>
 </xsl:for-each-group> </xsl:for-each-group>
The two approaches are not precisely equivalent. If
the code were changed to output the value of
position()
alongside @name
then
the first approach (a single xsl:for-each-group
element with a compound key) would number the groups (1,
2, 3), while the second approach (two nested xsl:for-each-group
elements) would number them (1, 2, 1).
The next example identifies a group not by the
presence of a common value, but rather by adjacency in
document order. A group consists of an h2
element, followed by all the p
elements up
to the next h2
element.
Source XML document:

Introduction

XSLT is used to write stylesheets.

XQuery is used to query XML databases.

What is a stylesheet?

A stylesheet is an XML document used to define a transformation.

Stylesheets may be written in XSLT.

XSLT 2.0 introduces new grouping constructs.

Desired output:
<chapter>
 <para>XSLT is used to write stylesheets.</para> <para>XQuery is used to query XML databases.</para>

 <para>A stylesheet is an XML document used to define a transformation.</para> <para>Stylesheets may be written in XSLT.</para> <para>XSLT 2.0 introduces new grouping constructs.</para>
 </chapter>
Solution:
<xsl:template match="body"> <chapter> <xsl:for-each-group select="*" group-starting-with="h2" >
 <xsl:for-each select="current-group()[self::p]"> <para><xsl:value-of select="."/></para> </xsl:for-each>
 </xsl:for-each-group> </chapter> </xsl:template>
The use of title="{self::h2}"
rather than
title="{.}"
is to handle the case where the
first element is not an h2
element.
The next example illustrates how a group of related
elements can be identified by the last element in the
group, rather than the first. Here the absence of the
attribute continued="yes"
indicates the end
of the group.
Source XML document:
<doc> <page continued="yes">Some text</page> <page continued="yes">More text</page> <page>Yet more text</page> <page continued="yes">Some words</page> <page continued="yes">More words</page> <page>Yet more words</page> </doc>
Desired output:
<doc> <pageset> <page>Some text</page> <page>More text</page> <page>Yet more text</page> </pageset> <pageset> <page>Some words</page> <page>More words</page> <page>Yet more words</page> </pageset> </doc>
Solution:
<xsl:template match="doc"> <doc> <xsl:for-each-group select="*" group-ending-with="page[not(@continued='yes')]"> <pageset> <xsl:for-each select="current-group()"> <page><xsl:value-of select="."/></page> </xsl:for-each> </pageset> </xsl:for-each-group> </doc> </xsl:template>
The next example shows how an item can be added to multiple groups. Book titles will be added to one group for each indexing term marked up within the title.
Source XML document:
<titles> <title>A Beginner's Guide to <ix>Java</ix></title> <title>Learning <ix>XML</ix></title> <title>Using <ix>XML</ix> with <ix>Java</ix></title> </titles>
Desired output:

Java

A Beginner's Guide to Java

Using XML with Java

XML

Learning XML

Using XML with Java

Solution:
<xsl:template match="titles"> <xsl:for-each-group select="title" group-by="ix">
<xsl:value-of select="current-grouping-key()"/>
 <xsl:for-each select="current-group()">
<xsl:value-of select="."/>
 </xsl:for-each> </xsl:for-each-group> </xsl:template>
In the final example, the membership of a node within a group is based both on adjacency of the nodes in document order, and on common values. In this case, the grouping key is a boolean condition, true or false, so the effect is that a grouping establishes a maximal sequence of nodes for which the condition is true, followed by a maximal sequence for which it is false, and so on.
Source XML document:

Do not:

talk,

eat, or

use your mobile telephone

 while you are in the cinema.

Desired output:

Do not:

talk,

eat, or

use your mobile telephone

while you are in the cinema.

Solution:
This requires creating a p
element around
the maximal sequence of sibling nodes that does not
include a ul
or ol
element.
This can be done by using group-adjacent
,
with a grouping key that is true if the element is a
ul
or ol
element, and false
otherwise:
<xsl:template match="p"> <xsl:for-each-group select="node()" group-adjacent="self::ul or self::ol"> <xsl:choose> <xsl:when test="current-grouping-key()"> <xsl:copy-of select="current-group()"/> </xsl:when> <xsl:otherwise>
 <xsl:copy-of select="current-group()"/>
 </xsl:otherwise> </xsl:choose> </xsl:for-each-group> </xsl:template>
The core function library for XPath 2.0 defines three functions that make use of regular expressions:
matches
FO returns a
boolean result that indicates whether or not a string
matches a given regular expression.
replace
FO takes a
string as input and returns a string obtained by
replacing all substrings that match a given regular
expression with a replacement string.
tokenize
FO returns a
sequence of strings formed by breaking a supplied input
string at any separator that matches a given regular
expression.
These functions are described in [Functions and Operators].
For more complex string processing than is possible using
these functions, XSLT provides an instruction xsl:analyze-string
,
which is defined in this section.
The regular expressions used by this instruction, and the flags that control the interpretation of these regular expressions, must conform to the syntax defined in [Functions and Operators] (see Section 7.6.1 Regular Expression SyntaxFO), which is itself based on the syntax defined in [XML Schema Part 2].
xsl:analyze-string
instruction
<xsl:analyze-string
select = expression
regex = { string }
flags? = { string }>

</xsl:analyze-string>
<xsl:matching-substring>

</xsl:matching-substring>
<xsl:non-matching-substring>

</xsl:non-matching-substring>
The xsl:analyze-string
instruction takes as input a string (the result of
evaluating the expression in the select
attribute) and a regular expression (the effective value of
the regex
attribute).
If the result of evaluating the select
expression is not a string, it is converted to a string by
applying the function conversion
rules.
The flags
attribute may be used to control
the interpretation of the regular expression. If the
attribute is omitted, the effect is the same as supplying a
zero-length string. This is interpreted in the same way as
the $flags
attribute of the functions matches
FO, replace
FO, and
tokenize
FO.
Specifically, if it contains the letter
m
, the match operates in multiline mode. If it
contains the letter s
, it operates in dot-all
mode. If it contains the letter i
, it operates
in case-insensitive mode. If it contains the letter
x
, then whitespace within the regular
expression is ignored. For more detailed specifications of
these modes, see [Functions and
Operators] (Section
<IP_ADDRESS> FlagsFO).
Note:
Because the regex
attribute is an
attribute value template, curly brackets within the
regular expression must be doubled. For example, to match
a sequence of one to five characters, write
regex=".{{1,5}}"
. For regular
expressions containing many curly brackets it may be more
convenient to use a notation such as
regex="{'[0-9]{1,5}[a-z]{3}[0-9]{1,2}'}"
, or
to use a variable.
The content of the xsl:analyze-string
instruction must take one of the following forms:
A single xsl:matching-substring
instruction, followed by zero or more xsl:fallback
instructions
A single xsl:non-matching-substring
instruction, followed by zero or more xsl:fallback
instructions
A single xsl:matching-substring
instruction, followed by a single xsl:non-matching-substring
instruction, followed by zero or more xsl:fallback
instructions
[ERR XTSE1130] It is a static error if
the xsl:analyze-string
instruction contains neither an xsl:matching-substring
nor an xsl:non-matching-substring
element.
Any xsl:fallback
elements
among the children of the xsl:analyze-string
instruction are ignored by an XSLT 2.0 processor,
but allow fallback behavior to be defined when the
stylesheet is used with an XSLT 1.0 processor operating in
forwards-compatible mode.
This instruction is designed to process all the non-overlapping substrings of the input string that match the regular expression supplied.
[ERR XTDE1140] It is a non-recoverable dynamic
error if the effective value of the
regex
attribute does not conform to the
required syntax for regular
expressions, as specified in [Functions and Operators]. If the
regular expression is known statically (for example, if the
attribute does not contain any expressions enclosed in curly
brackets) then the processor may
signal the error as a static error.
[ERR XTDE1145] It is a non-recoverable dynamic
error if the effective value of the
flags
attribute has a value other than the
values defined in [Functions and
Operators]. If the value of the attribute is known
statically (for example, if the attribute does not contain
any expressions enclosed in curly
brackets) then the processor may
signal the error as a static error.
[ERR XTDE1150] It is a non-recoverable dynamic
error if the effective value of the
regex
attribute is a regular expression that
matches a zero-length string: or more specifically, if the
regular expression $r
and flags
$f
are such that matches("", $r,
$f)
returns true. If the regular expression is known
statically (for example, if the attribute does not contain
any expressions enclosed in curly
brackets) then the processor may
signal the error as a static error.
The xsl:analyze-string
instruction starts at the beginning of the input string and
attempts to find the first substring that matches the
regular expression. If there are several matches, the first
match is defined to be the one whose starting position
comes first in the string. If several alternatives within
the regular expression both match at the same position in
the input string, then the match that is chosen is the
first alternative that matches. For example, if the input
string is The quick brown fox jumps
and the
regular expression is jump|jumps
, then the
match that is chosen is jump
.
Having found the first match, the instruction proceeds to find the second and subsequent matches by repeating the search, starting at the first character that was not included in the previous match.
The input string is thus partitioned into a sequence of
substrings, some of which match the regular expression,
others which do not match it. Each substring will contain
at least one character. This sequence of substrings is
processed using the xsl:matching-substring
and xsl:non-matching-substring
child instructions. A matching substring is processed using
the xsl:matching-substring
element, a non-matching substring using the xsl:non-matching-substring
element. Each of these elements takes a sequence
constructor as its content. If the element is absent, the
effect is the same as if it were present with empty
content. In processing each substring, the contents of the
substring will be the context item (as a value of type
xs:string
); the position of the substring
within the sequence of matching and non-matching substrings
will be the context position; and the number
of matching and non-matching substrings will be the
context
size.
If the input is a zero-length string, the number of
substrings will be zero, so neither the xsl:matching-substring
nor xsl:non-matching-substring
elements will be evaluated.
regex-group
($group-number
as
xs:integer
) as
xs:string
[Definition: While the xsl:matching-substring
instruction is active, a set of current captured
substrings is available, corresponding to the
parenthesized sub-expressions of the regular
expression.] These captured
substrings are accessible using the function regex-group
. This
function takes an integer argument to identify the group,
and returns a string representing the captured
substring.
The Nth captured substring (where
N > 0) is the string matched by the
subexpression contained by the Nth left
parenthesis in the regex. The zeroeth captured substring is
the string that matches the entire regex. This means that
the value of regex-group(0)
is initially the
same as the value of .
(dot).
The function returns the zero-length string if there is no captured substring with the relevant number. This can occur for a number of reasons:
The number is negative.
The regular expression does not contain a parenthesized sub-expression with the given number.
The parenthesized sub-expression exists, and did not match any part of the input string.
The parenthesized sub-expression exists, and matched a zero-length substring of the input string.
The set of captured substrings is a context variable
with dynamic scope. It is initially an empty sequence.
During the evaluation of an xsl:matching-substring
instruction it is set to the sequence of matched substrings
for that regex match. During the evaluation of an xsl:non-matching-substring
instruction or a pattern or a stylesheet function it is set
to an empty sequence. On completion of an instruction that
changes the value, the variable reverts to its previous
value.
The value of the current captured
substrings is unaffected through calls of xsl:apply-templates
,
xsl:call-template
,
xsl:apply-imports
or xsl:next-match
, or
by expansion of named attribute sets.
Problem: replace all newline characters in the
abstract
element by empty br
elements:
Solution:
<xsl:analyze-string select="abstract" regex="\n"> <xsl:matching-substring>
 </xsl:matching-substring> <xsl:non-matching-substring> <xsl:value-of select="."/> </xsl:non-matching-substring> </xsl:analyze-string>
Problem: replace all occurrences of [...]
in the body
by cite
elements,
retaining the content between the square brackets as the
content of the new element.
Solution:
<xsl:analyze-string select="body" regex="\[(.*?)\]"> <xsl:matching-substring> <xsl:value-of select="regex-group(1)"/> </xsl:matching-substring> <xsl:non-matching-substring> <xsl:value-of select="."/> </xsl:non-matching-substring> </xsl:analyze-string>
Note that this simple approach fails if the
body
element contains markup that needs to
be retained. In this case it is necessary to apply the
regular expression processing to each text node
individually. If the [...]
constructs span
multiple text nodes (for example, because there are
elements within the square brackets) then it probably
becomes necessary to make two or more passes over the
data.
Problem: the input string contains a date such as
23 March 2002
. Convert it to the form
2002-03-23
.
Solution (with no error handling if the input format is incorrect):
<xsl:variable name="months" select="'January', 'February', 'March', ..."/> <xsl:analyze-string select="normalize-space($input)" regex="([0-9]{{1,2}})\s([A-Z][a-z]+)\s([0-9]{{4}})"> <xsl:matching-substring> <xsl:number value="regex-group(3)" format="0001"/> <xsl:text>-</xsl:text> <xsl:number value="index-of($months, regex-group(2))" format="01"/> <xsl:text>-</xsl:text> <xsl:number value="regex-group(1)" format="01"/> </xsl:matching-substring> </xsl:analyze-string>
Note the use of normalize-space
to
simplify the work done by the regular expression, and the
use of doubled curly brackets because the
regex
attribute is an attribute value
template.
This section describes XSLT-specific additions to the core function library. Some of these additional functions also make use of information specified by declarations in the stylesheet; this section also describes these declarations.
document
($uri-sequence
as
item()*
) as
node()*
document
($uri-sequence
as
item()*
, $base-node
as
node()
) as
node()*
The document
function
allows access to XML documents identified by a URI.
The first argument contains a sequence of URI references. The second argument, if present, is a node whose base URI is used to resolve any relative URI references contained in the first argument.
A sequence of absolute URI references is obtained as follows.
For an item in $uri-sequence
that is an
instance of xs:string
,
xs:anyURI
, or
xs:untypedAtomic
, the value
is cast to xs:anyURI
. If the resulting URI
reference is an absolute URI reference then it is used
as is. If it is a relative URI reference, then
it is resolved against the base URI of
$base-node
if supplied, or against the
base URI from the static context otherwise (this will
usually be the base URI of the stylesheet module). A
relative URI is resolved against a base URI using the
rules defined in [RFC3986].
For an item in $uri-sequence
that is a
node, the node is atomized. The result must be a sequence whose items are all
instances of xs:string
,
xs:anyURI
, or
xs:untypedAtomic
. Each of
these values is cast to xs:anyURI
, and if
the resulting URI reference is an absolute URI
reference then it is used as is. If it is a
relative URI reference, then it is resolved against the
base URI of $base-node
if supplied, or
against the base URI of the node that contained it
otherwise.
Note:
The XPath rules for function calling ensure that it is a type error if the supplied value of the second argument is anything other than a single node. If XPath 1.0 compatibility mode is enabled, then a sequence of nodes may be supplied, and the first node in the sequence will be used.
Each of these absolute URI references is then processed
as follows. Any fragment identifier that is present in the
URI reference is removed, and the resulting absolute URI is
cast to a string and then passed to the doc
FO function defined in [Functions and Operators]. This
returns a document node. If an error occurs during
evaluation of the doc
FO function, the processor
may either signal this error in
the normal way, or may recover by
ignoring the failure, in which case the failing URI will
not contribute any nodes to the result of the document
function.
If the URI reference contained no fragment identifier,
then this document node is included in the sequence of
nodes returned by the document
function.
If the URI reference contained a fragment identifier, then the fragment identifier is interpreted according to the rules for the media type of the resource representation identified by the URI, and is used to select zero or more nodes that are descendant-or-self nodes of the returned document node. As described in 2.3 Initiating a Transformation, the media type is available as part of the evaluation context for a transformation.
[ERR XTRE1160] When a URI reference contains a fragment identifier, it is a recoverable dynamic error if the media type is not one that is recognized by the processor, or if the fragment identifier does not conform to the rules for fragment identifiers for that media type, or if the fragment identifier selects something other than a sequence of nodes (for example, if it selects a range of characters within a text node). The optional recovery action is to ignore the fragment identifier and return the document node. The set of media types recognized by a processor is implementation-defined.
Note:
The recovery action here is different from XSLT 1.0
The sequence of nodes returned by the function is in
document order, with no duplicates. This order has no
necessary relationship to the order in which URIs were
supplied in the $uri-sequence
argument.
Note:
One effect of these rules is that unless XML entities
or xml:base
are used, and provided that the
base URI of the stylesheet module is known,
document("")
refers to the document node of
the containing stylesheet module (the definitive rules
are in [RFC3986]).
The XML resource containing the stylesheet module is
processed exactly as if it were any other XML document,
for example there is no special recognition of xsl:text
elements, and
no special treatment of comments and processing
instructions.
unparsed-text
($href
as
xs:string?
) as
xs:string?
unparsed-text
($href
as
xs:string?
, $encoding
as
xs:string
) as
xs:string?
The unparsed-text
function reads an external resource (for example, a file)
and returns its contents as a string.
The $href
argument must be a string in the form of a
URI. The URI must contain
no fragment identifier, and must
identify a resource that can be read as text. If the URI is
a relative URI, then it is resolved relative to the base
URI from the static context.
If the value of the $href
argument is an
empty sequence, the function returns an empty sequence.
Note:
If a different base URI is appropriate (for example,
when resolving a relative URI read from a source
document) then the relative URI should be resolved using
the
resolve-uri
FO
function before passing it to the unparsed-text
function.
The $encoding
argument, if present, is the
name of an encoding. The values for this attribute follow
the same rules as for the encoding
attribute
in an XML declaration. The only values which every
implementation is required to recognize are utf-8
and utf-16
.
The encoding of the external resource is determined as follows:
external encoding information is used if available, otherwise
if the media type of the resource is
text/xml
or application/xml
(see [RFC2376]), or if it
matches the conventions text/*+xml
or
application/*+xml
(see [RFC3023] and/or its
successors), then the encoding is recognized as
specified in [XML 1.0],
otherwise
the value of the $encoding
argument is
used if present, otherwise
the processor may use implementation-defined heuristics to determine the likely encoding, otherwise
UTF-8 is assumed.
Note:
The above rules are chosen for consistency with [XInclude]. Files with an XML media type are treated specially because there are use cases for this function where the retrieved text is to be included as unparsed XML within a CDATA section of a containing document, and because processors are likely to be able to reuse the code that performs encoding detection for XML external entities.
[ERR XTDE1170] It is a non-recoverable dynamic error if a URI contains a fragment identifier, or if it cannot be used to retrieve a resource containing text.
[ERR XTDE1190] It is a non-recoverable dynamic error if a resource contains octets that cannot be decoded into Unicode characters using the specified encoding, or if the resulting characters are not permitted XML characters. This includes the case where the processor does not support the requested encoding.
[ERR XTDE1200] It is a non-recoverable dynamic
error if the second argument of the unparsed-text
function is omitted and the processor cannot infer the encoding
using external information and the encoding is not
UTF-8.
The result is a string containing the text of the resource retrieved using the URI.
Note:
If the text file contains characters such as
<
and &
, these will
typically be output as <
and
&
when the string is written to a
final result tree and
serialized as XML or HTML. If these characters actually
represent markup (for example, if the text file contains
HTML), then the stylesheet can attempt to write them as
markup to the output file using the
disable-output-escaping
attribute of the
xsl:value-of
instruction (see 20.2 Disabling Output
Escaping). Note, however, that implementations
are not required to support this feature.
This example attempts to read an HTML file and copy it, as HTML, to the serialized output file:
<xsl:output method="html"/> <xsl:template match="/"> <xsl:value-of select="unparsed-text('header.html', 'iso-8859-1')" disable-output-escaping="yes"/> <xsl:apply-templates/> <xsl:value-of select="unparsed-text('footer.html', 'iso-8859-1')" disable-output-escaping="yes"/> </xsl:template>
Often it is necessary to split a text file into a
sequence of lines, representing each line as a string.
This can be achieved by using the unparsed-text
function in conjunction with the XPath
tokenize
FO function.
For example:
<xsl:for-each select="tokenize(unparsed-text($in), '\r?\n')"> ... </xsl:for-each>
Note that the unparsed-text
function does not normalize line endings. This example
has therefore been written to recognize both Unix and
Windows conventions for end-of-line, namely a single
newline (#x0A) character or a carriage return / line feed
pair (#x0D #x0A).
Because errors in evaluating the unparsed-text
function are non-recoverable, two functions are provided to
allow a stylesheet to determine whether a call with
particular arguments would succeed:
unparsed-text-available
($href
as
xs:string?
) as
xs:boolean
unparsed-text-available ( |
$href |
as xs:string? , |
$encoding |
as xs:string? ) as xs:boolean |
The unparsed-text-available
function determines whether a call on the unparsed-text
function with identical arguments would return a
string.
If the first argument is an empty sequence, the function returns false. If the second argument is an empty sequence, the function behaves as if the second argument were omitted.
In other cases, the function returns true if a call on
unparsed-text
with the same arguments would succeed, and false if a call
on unparsed-text
with the same arguments would fail with a non-recoverable
dynamic error.
Note:
This requires that the unparsed-text-available
function should actually attempt to read the resource
identified by the URI, and check that it is correctly
encoded and contains no characters that are invalid in
XML. Implementations may avoid the cost of repeating
these checks for example by caching the validated
contents of the resource, to anticipate a subsequent call
on the unparsed-text
function. Alternatively, implementations may be able to
rewrite an expression such as if
(unparsed-text-available(A)) then unparsed-text(A) else
...
to generate a single call internally.
The functions unparsed-text
and unparsed-text-available
have the same requirement for stability as the functions
doc
FO and
doc-available
FO
defined in [Functions and
Operators]. This means that unless the user has
explicitly stated a requirement for a reduced level of
stability, either of these functions if called twice with
the same arguments during the course of a transformation
must return the same results each
time; moreover, the results of a call on unparsed-text-available
must be consistent with the
results of a subsequent call on unparsed-text
with the same arguments.
Keys provide a way to work with documents that contain an implicit cross-reference structure. They make it easier to locate the nodes within a document that have a given value for a given attribute or child element, and they provide a hint to the implementation that certain access paths in the document need to be efficient.
xsl:key
Declaration
<xsl:key
name = qname
match = pattern
use? = expression
collation? = uri>

</xsl:key>
The xsl:key
declaration is used to declare
keys. The
name
attribute specifies the name of the
key. The value of the name
attribute is a
QName, which is
expanded as described in 5.1
Qualified Names. The match
attribute
is a Pattern; an xsl:key
element applies
to all nodes that match the pattern specified in the
match
attribute.
[Definition: A key is defined as a
set of xsl:key
declarations in the stylesheet that share the same
name.]
The value of the key may be specified either using the
use
attribute or by means of the contained
sequence constructor.
[ERR XTSE1205] It is a static error
if an xsl:key
declaration has a use
attribute and has
non-empty content, or if it has empty content and no
use
attribute.
If the use
attribute is present, its
value is an expression specifying the values of
the key. The expression will be evaluated with the node
that matches the pattern as the context node. The result
of evaluating the expression is atomized.
Similarly, if a sequence constructor is present, it is used to determine the values of the key. The sequence constructor will be evaluated with the node that matches the pattern as the context node. The result of evaluating the sequence constructor is atomized.
[Definition: The expression in the
use
attribute and the sequence constructor
within an xsl:key
declaration are referred to collectively as the key
specifier. The key specifier determines the values
that may be used to find a node using this key.]
Note:
There is no requirement that all the values of a key should have the same type.
The presence of an xsl:key
declaration makes
it easy to find a node that matches the
match
pattern if any of the values of the
key specifier (when
applied to that node) are known. It also provides a hint
to the implementation that access to the nodes by means
of these values needs to be efficient (many
implementations are likely to construct an index or hash
table to achieve this). Note that the key
specifier in general returns a sequence of
values, and any one of these may be used to locate the
node.
Note:
An xsl:key
declaration is not bound to a specific source document.
The source document to which it applies is determined
only when the key
function is used
to locate nodes using the key. Keys can be used to
locate nodes within any source document (including
temporary trees), but each use of the key
function searches
one document only.
The optional collation
attribute is used
only when deciding whether two strings are equal for the
purposes of key matching. Specifically, two values
$a
and $b
are considered equal
if the result of the function call compare($a, $b,
$collation)
is zero. The effective collation for
an xsl:key
declaration is the collation specified in its
collation
attribute if present,
resolved against the base URI of the xsl:key
element,
or the default collation that is in
scope for the xsl:key
declaration
otherwise; the effective collation must be the same for
all the xsl:key
declarations making up a key.
[ERR XTSE1210] It is a static error if
the xsl:key
declaration has a collation
attribute whose
value (after resolving against the base URI)
is not a URI recognized by the implementation as
referring to a collation.
[ERR XTSE1220] It is a static error if
there are several xsl:key
declarations in
the stylesheet with the same key name
and different effective collations. Two collations are
the same if their URIs are equal under the rules for
comparing xs:anyURI
values, or if the
implementation can determine that they are different URIs
referring to the same collation.
It is possible to have:
multiple xsl:key
declarations
with the same name;
a node that matches the match
patterns of several different xsl:key
declarations, whether these have the same key
name or different key names;
a node that returns more than one value from its key specifier;
a key value that identifies more than one node (the key values for different nodes do not need to be unique).
An xsl:key
declaration with higher import precedence does
not override another of lower import precedence; all the
xsl:key
declarations in the stylesheet are effective regardless
of their import precedence.
key
Functionkey
($key-name
as
xs:string
, $key-value
as
xs:anyAtomicType*
) as
node()*
key ( |
$key-name |
as xs:string , |
$key-value |
as xs:anyAtomicType* , |
|
$top |
as node() ) as node()* |
The key
function does for keys what the id
FO function does for IDs.
The $key-name
argument specifies the name
of the key. The value
of the argument must be a
lexical
QName, which is expanded as described in 5.1 Qualified Names.
[ERR XTDE1260] It is a non-recoverable dynamic
error if the value is not a valid QName, or if there
is no namespace declaration in scope for the prefix of
the QName, or if the name obtained by expanding the QName
is not the same as the expanded name of any xsl:key
declaration in
the stylesheet. If the processor is able
to detect the error statically (for example, when the
argument is supplied as a string literal), then the
processor may optionally signal
this as a static error.
The $key-value
argument to the key
function is
considered as a sequence. The set of requested key values
is formed by atomizing the supplied value of the
argument, using the standard function conversion
rules. Each of the resulting atomic values is
considered as a requested key value. The result of the
function is a sequence of nodes, in document order and
with duplicates removed, comprising those nodes in the
selected subtree (see below) that are
matched by an xsl:key
declaration whose
name is the same as the supplied key name, where the
result of evaluating the key specifier contains a value
that is equal to one of these requested key values, under
the rules appropriate to the XPath eq
operator for the two values in question, using the
collation
attributes of the xsl:key
declaration when
comparing strings. No error is reported if two values are
encountered that are not comparable; they are regarded
for the purposes of this function as being not equal.
Note:
Under the rules for the eq
operator,
untyped atomic values are converted to strings, not to
the type of the other operand. This means, for example,
that if the expression in the use
attribute returns a date, supplying an untyped atomic
value in the call to the key
function will
return an empty sequence.
If the second argument is an empty sequence, the result of the function will be an empty sequence.
Different rules apply when backwards
compatible behavior is enabled. Specifically, if any
of the xsl:key
elements in the definition of the key enables backwards compatible behavior,
then the value of the key specifier and the value of
the second argument of the key
function are both
converted after atomization to a sequence of strings, by
applying a cast to each item in the sequence, before
performing the comparison.
The third argument is used to identify the selected
subtree. If the argument is present, the selected subtree
is the set of nodes that have $top as an
ancestor-or-self node. If the argument is omitted, the
selected subtree is the document containing the context
node. This means that the third argument effectively
defaults to /
.
[ERR XTDE1270] It is a non-recoverable dynamic
error to call the key
function with two
arguments if there is no context node, or if the root
of the tree containing the context node is not a document
node; or to call the function with three arguments
if the root of the tree containing the node supplied in
the third argument is not a document node.
The result of the key
function can be
described more specifically as follows. The result is a
sequence containing every node $N that
satisfies the following conditions:
$N/ancestor-or-self::node() intersect
$top
is non-empty. (If the third argument is
omitted, $top
defaults to
/
)
$N matches the pattern specified in the
match
attribute of an xsl:key
declaration
whose name
attribute matches the name
specified in the $key-name
argument.
When the key specifier of that
xsl:key
declaration is evaluated with a singleton focus based on
$N, the atomized value of the resulting
sequence includes a value that compares equal to at
least one item in the atomized value of the sequence
supplied as $key-value
, under the rules
of the eq
operator with the collation
selected as described above.
The sequence returned by the key
function will be in
document order, with duplicates (that is, nodes having
the same identity) removed.
For example, given a declaration
<xsl:key name="idkey" match="div" use="@id"/>
an expression key("idkey",@ref)
will
return the same nodes as id(@ref)
,
assuming that the only ID attribute declared in the XML
source document is:
<!ATTLIST div id ID #IMPLIED>
and that the ref
attribute of the
context node contains no whitespace.
Suppose a document describing a function library
uses a prototype
element to define
functions
<prototype name="sqrt" return-type="xs:double"> <arg type="xs:double"/> </prototype>
and a function
element to refer to
function names
<function>sqrt</function>
Then the stylesheet could generate hyperlinks between the references and definitions as follows:
<xsl:key name="func" match="prototype" use="@name"/> <xsl:template match="function">   <xsl:apply-templates/>   </xsl:template> <xsl:template match="prototype">
  Function:  ...
 </xsl:template>
When called with two arguments, the key
function always
returns nodes that are in the same document as the
context node. To retrieve a node from any other document,
it is necessary either to change the context node, or to
supply a third argument.
For example, suppose a document contains
bibliographic references in the form
<bibref>XSLT</bibref>
, and
there is a separate XML document bib.xml
containing a bibliographic database with entries in the
form:
<entry name="XSLT">...</entry>
Then the stylesheet could use the following to
transform the bibref
elements:
<xsl:key name="bib" match="entry" use="@name"/> <xsl:template match="bibref"> <xsl:variable name="name" select="."/> <xsl:apply-templates select="document('bib.xml')/key('bib',$name)"/> </xsl:template>
Note:
This relies on the ability in XPath 2.0 to have a
function call on the right-hand side of the
/
operator in a path expression.
The following code would also work:
<xsl:key name="bib" match="entry" use="@name"/> <xsl:template match="bibref"> <xsl:apply-templates select="key('bib', ., document('bib.xml'))"/> </xsl:template>
format-number
($value
as
numeric?
, $picture
as
xs:string
) as
xs:string
format-number ( |
$value |
as numeric? , |
$picture |
as xs:string , |
|
$decimal-format-name |
as xs:string ) as xs:string |
The format-number
function formats $value
as a string using the
picture
string specified by the $picture
argument
and the decimal-format named by the
$decimal-format-name
argument, or the default
decimal-format, if there is no
$decimal-format-name
argument. The
syntax of the picture string is described in 16.4.2 Processing the
Picture String.
The $value
argument may be of any numeric
data type (xs:double
, xs:float
,
xs:decimal
, or their subtypes including
xs:integer
). Note that if an
xs:decimal
is supplied, it is not
automatically promoted to an xs:double
, as
such promotion can involve a loss of precision.
If the supplied value of the $value
argument is an empty sequence, the function behaves as if
the supplied value were the xs:double
value
NaN
.
The value of $decimal-format-name
must be a lexical QName,
which is expanded as described in 5.1
Qualified Names. The result of the function is the
formatted string representation of the supplied number.
[ERR XTDE1280] It is a non-recoverable dynamic
error if the name specified as the
$decimal-format-name
argument is not a
valid QName, or if
its prefix has not been declared in an in-scope namespace
declaration, or if the stylesheet does not contain a
declaration of a decimal-format with a matching expanded-QName. If the processor
is able to detect the error statically (for example, when
the argument is supplied as a string literal), then the
processor may optionally signal
this as a static error.

<xsl:decimal-format
name? = qname
decimal-separator? = char
grouping-separator? = char
infinity? = string
minus-sign? = char
NaN? = string
percent? = char
per-mille? = char
zero-digit? = char
digit? = char
pattern-separator? =
char />
The xsl:decimal-format
element controls the interpretation of a picture
string used by the format-number
function.
A stylesheet may contain multiple
xsl:decimal-format
declarations and may include or import stylesheet modules that also
contain xsl:decimal-format
declarations. The name of an xsl:decimal-format
declaration is the value of its name
attribute, if any.
[Definition: All the xsl:decimal-format
declarations in a stylesheet that share the same name are
grouped into a named decimal format; those that
have no name are grouped into a single unnamed decimal
format.]
If a stylesheet does not contain a
declaration of the unnamed decimal format, a declaration
equivalent to an xsl:decimal-format
element with no attributes is implied.
The attributes of the xsl:decimal-format
declaration establish values for a number of variables
used as input to the algorithm followed by the format-number
function. An outline of the purpose of each attribute is
given below; however, the definitive explanations are
given later, as part of the description of this
algorithm.
For any named decimal format, the effective
value of each attribute is taken from an xsl:decimal-format
declaration that has that name, and that specifies an
explicit value for the required attribute. If there is no
such declaration, the default value of the attribute is
used. If there is more than one such declaration, the one
with highest import precedence is
used.
For any unnamed decimal format, the effective
value of each attribute is taken from an xsl:decimal-format
declaration that is unnamed, and that specifies an
explicit value for the required attribute. If there is no
such declaration, the default value of the attribute is
used. If there is more than one such declaration, the one
with highest import precedence is
used.
[ERR XTSE1290] It is a static error
if a named or unnamed decimal format contains two
conflicting values for the same attribute in different
xsl:decimal-format
declarations having the same import precedence,
unless there is another definition of the same attribute
with higher import precedence.
The following attributes control the interpretation of
characters in the picture string supplied to the
format-number
function, and also specify characters that may appear in
the result of formatting the number. In each case the
value must be a single
character [see ERR XTSE0020].
decimal-separator
specifies the
character used for the
decimal-separator-sign; the default value
is the period character (.
)
grouping-separator
specifies the
character used for the grouping-sign,
which is typically used as a thousands separator; the
default value is the comma character
(,
)
percent
specifies the character used
for the percent-sign; the default value is
the percent character (%
)
per-mille
specifies the character
used for the per-mille-sign; the default
value is the Unicode per-mille character (#x2030)
zero-digit
specifies the character
used for the digit-zero-sign; the default
value is the digit zero (0
). This
character must be a digit
(category Nd in the Unicode property database), and
it must have the numeric
value zero. This attribute implicitly defines
the Unicode character that is used to represent each
of the values 0 to 9 in the final result string:
Unicode is organized so that each set of decimal
digits forms a contiguous block of characters in
numerical sequence.
[ERR XTSE1295] It is a static error
if the character specified in the zero-digit
attribute is not a digit or is a digit that does not have
the numeric value zero.
The following attributes control the interpretation of
characters in the picture string supplied to the
format-number
function. In each case the value must be a single character
[see ERR XTSE0020].
digit
specifies the character used
for the digit-sign in the picture
string; the default value is the number sign
character (#
)
pattern-separator
specifies the
character used for the
pattern-separator-sign, which separates
positive and negative sub-pictures in a picture
string; the default value is the semi-colon
character (;
)
The following attributes specify characters or strings that may appear in the result of formatting the number:
infinity
specifies the string used
for the infinity-symbol; the default value
is the string Infinity
NaN
specifies the string used for the
NaN-symbol, which is used to represent the
value NaN (not-a-number); the default value is the
string NaN
minus-sign
specifies the character
used for the minus-symbol; the default
value is the hyphen-minus character (-
,
#x2D). The value must be a
single character.
[ERR XTSE1300] It is a static error if, for any named or unnamed decimal format, the variables representing characters used in a picture string do not each have distinct values. These variables are decimal-separator-sign, grouping-sign, percent-sign, per-mille-sign, digit-zero-sign, digit-sign, and pattern-separator-sign.
[Definition: The formatting of a number is controlled by a picture string. The picture string is a sequence of characters, in which the characters assigned to the variables decimal-separator-sign, grouping-sign, zero-digit-sign, digit-sign and pattern-separator-sign are classified as active characters, and all other characters (including the percent-sign and per-mille-sign) are classified as passive characters.]
The integer part of the sub-picture is defined as the part that appears to the left of the decimal-separator-sign if there is one, or the entire sub-picture otherwise. The fractional part of the sub-picture is defined as the part that appears to the right of the decimal-separator-sign if there is one; it is a zero-length string otherwise.
[ERR XTDE1310] The picture string must conform to the following rules. It is a non-recoverable dynamic error if the picture string does not satisfy these rules.
Note that in these rules the words "preceded" and "followed" refer to characters anywhere in the string, they are not to be read as "immediately preceded" and "immediately followed".
A picture-string consists either of a sub-picture, or of two sub-pictures separated by a pattern-separator-sign. A picture-string must not contain more than one pattern-separator-sign. If the picture-string contains two sub-pictures, the first is used for positive values and the second for negative values.
A sub-picture must not contain more than one decimal-separator-sign.
A sub-picture must not contain more than one percent-sign or per-mille-sign, and it must not contain one of each.
A sub-picture must contain at least one digit-sign or zero-digit-sign.
A sub-picture must not contain a passive character that is preceded by an active character and that is followed by another active character.
A sub-picture must not contain a grouping-separator-sign adjacent to a decimal-separator-sign.
The integer part of a sub-picture must not contain a zero-digit-sign that is followed by a digit-sign. The fractional part of a sub-picture must not contain a digit-sign that is followed by a zero-digit-sign.
The evaluation of the format-number
function is described below in two phases, an analysis
phase and a formatting phase. The analysis phase takes as
its inputs the picture string and the variables
derived from the relevant xsl:decimal-format
declaration, and produces as its output a number of
variables with defined values. The formatting phase takes
as its inputs the number to be formatted and the
variables produced by the analysis phase, and produces as
its output a string containing a formatted representation
of the number.
Note:
Numbers will always be formatted with the most significant digit on the left.
This phase of the algorithm analyses the picture
string and the attribute settings of the xsl:decimal-format
declaration, and has the effect of setting the values of
various variables, which are used in the subsequent
formatting phase. These variables are listed below. Each
is shown with its initial setting and its data type.
Several variables are associated with each sub-picture. If there are two sub-pictures, then these rules are applied to one sub-picture to obtain the values that apply to positive numbers, and to the other to obtain the values that apply to negative numbers. If there is only one sub-picture, then the values for both cases are derived from this sub-picture.
The variables are as follows:
The integer-part-grouping-positions is a sequence of integers representing the positions of grouping separators within the integer part of the sub-picture. For each grouping-separator-sign that appears within the integer part of the sub-picture, this sequence contains an integer that is equal to the total number of digit-sign and zero-digit-sign characters that appear within the integer part of the sub-picture and to the right of the grouping-separator-sign. In addition, if these integer-part-grouping-positions are at regular intervals (that is, if they form a sequence N, 2N, 3N, ... for some integer value N, including the case where there is only one number in the list), then the sequence contains all integer multiples of N as far as necessary to accommodate the largest possible number.
The minimum-integer-part-size is an integer indicating the minimum number of digits that will appear to the left of the decimal-separator-sign. It is normally set to the number of zero-digit-sign characters found in the integer part of the sub-picture. But if the sub-picture contains no zero-digit-sign and no decimal-separator-sign, it is set to one.
Note:
There is no maximum integer part size. All significant digits in the integer part of the number will be displayed, even if this exceeds the number of digit-sign and zero-digit-sign characters in the subpicture.
The prefix is set to contain all passive characters in the sub-picture to the left of the leftmost active character. If the picture string contains only one sub-picture, the prefix for the negative sub-picture is set by concatenating the minus-sign character and the prefix for the positive sub-picture (if any), in that order.
The fractional-part-grouping-positions is a sequence of integers representing the positions of grouping separators within the fractional part of the sub-picture. For each grouping-separator-sign that appears within the fractional part of the sub-picture, this sequence contains an integer that is equal to the total number of digit-sign and zero-digit-sign characters that appear within the fractional part of the sub-picture and to the left of the grouping-separator-sign.
The minimum-fractional-part-size is set to the number of zero-digit-sign characters found in the fractional part of the sub-picture.
The maximum-fractional-part-size is set to the total number of digit-sign and zero-digit-sign characters found in the fractional part of the sub-picture.
The suffix is set to contain all passive characters to the right of the rightmost active character in the fractional part of the sub-picture.
Note:
If there is only one sub-picture, then all variables for positive numbers and negative numbers will be the same, except for prefix: the prefix for negative numbers will be preceded by the minus-sign character.
This section describes the second phase of processing
of the format-number
function. This phase takes as input a number to be
formatted (referred to as the input number), and
the variables set up by analysing the xsl:decimal-format
declaration and the picture string, as described
above. The result of this phase is a string, which forms
the return value of the format-number
function.
The algorithm for this second stage of processing is as follows:
If the input number is NaN (not a number), the result is the specified NaN-symbol (with no prefix or suffix).
In the rules below, the positive sub-picture and its associated variables are used if the input number is positive, and the negative sub-picture and its associated variables are used otherwise. Negative zero is taken as negative, positive zero as positive.
If the input number is positive or negative infinity, the result is the concatenation of the appropriate prefix, the infinity-symbol, and the appropriate suffix.
If the sub-picture contains a percent-sign, the number is multiplied by 100. If the sub-picture contains a per-mille-sign, the number is multiplied by 1000. The resulting number is referred to below as the adjusted number.
The adjusted number is converted (if
necessary) to an xs:decimal
value, using
an implementation of xs:decimal
that
imposes no limits on the totalDigits
or
fractionDigits
facets. If there are
several such values that are numerically equal to the
adjusted number (bearing in mind that if
the adjusted number is an
xs:double
or xs:float
, the
comparison will be done by converting the decimal
value back to an xs:double
or
xs:float
), the one that is chosen
should be one with the
smallest possible number of digits not counting
leading or trailing zeroes (whether significant
or insignificant). For example, 1.0 is
preferred to 0.9999999999, and 100000000 is preferred
to 100000001. This value is then rounded so that it
uses no more than
maximum-fractional-part-size
digits in
its fractional part. The rounded number is
defined to be the result of converting the
adjusted number to an
xs:decimal
value, as described above,
and then calling the function
round-half-to-even
FO
with this converted number as the first argument and
the maximum-fractional-part-size
as the
second argument, again with no limits on the
totalDigits
or
fractionDigits
in the result.
The absolute value of the rounded number is converted to a string in decimal notation, with no insignificant leading or trailing zeroes, using the characters implied by the choice of zero-digit-sign to represent the ten decimal digits, and the decimal-separator-sign to separate the integer part and the fractional part. (The value zero will at this stage be represented by a decimal-separator-sign on its own.)
If the number of digits to the left of the decimal-separator-sign is less than minimum-integer-part-size, leading zero-digit-sign characters are added to pad out to that size.
If the number of digits to the right of the decimal-separator-sign is less than minimum-fractional-part-size, trailing zero-digit-sign characters are added to pad out to that size.
For each integer N in the integer-part-grouping-positions list, a grouping-separator-sign character is inserted into the string immediately after that digit that appears in the integer part of the number and has N digits between it and the decimal-separator-sign, if there is such a digit.
For each integer N in the fractional-part-grouping-positions list, a grouping-separator-sign character is inserted into the string immediately before that digit that appears in the fractional part of the number and has N digits between it and the decimal-separator-sign, if there is such a digit.
If there is no decimal-separator-sign in the sub-picture, or if there are no digits to the right of the decimal-separator-sign character in the string, then the decimal-separator-sign character is removed from the string (it will be the rightmost character in the string).
The result of the function is the concatenation of the appropriate prefix, the string conversion of the number as obtained above, and the appropriate suffix.
Three functions are provided to represent dates and times as a string, using the conventions of a selected calendar, language, and country. Each has two variants.
format-dateTime ( |
$value |
as xs:dateTime? , |
$picture |
as xs:string , |
|
$language |
as xs:string? , |
|
$calendar |
as xs:string? , |
|
$country |
as xs:string? ) as xs:string? |
format-dateTime
($value
as
xs:dateTime?
, $picture
as
xs:string
) as
xs:string?
format-date ( |
$value |
as xs:date? , |
$picture |
as xs:string , |
|
$language |
as xs:string? , |
|
$calendar |
as xs:string? , |
|
$country |
as xs:string? ) as xs:string? |
format-date
($value
as
xs:date?
, $picture
as
xs:string
) as
xs:string?
format-time ( |
$value |
as xs:time? , |
$picture |
as xs:string , |
|
$language |
as xs:string? , |
|
$calendar |
as xs:string? , |
|
$country |
as xs:string? ) as xs:string? |
format-time
($value
as
xs:time?
, $picture
as
xs:string
) as
xs:string?
The format-dateTime
,
format-date
, and
format-time
functions format $value
as a string using the
picture string specified by the $picture
argument, the calendar specified by the
$calendar
argument, the language specified by
the $language
argument, and the country
specified by the $country
argument. The result
of the function is the formatted string representation of
the supplied dateTime
, date
, or
time
value.
[Definition: The three functions format-date
,
format-time
, and
format-dateTime
are referred to collectively as the date formatting
functions.]
If $value
is the empty sequence, the empty
sequence is returned.
Calling the two-argument form of each of the three functions is equivalent to calling the five-argument form with each of the last three arguments set to an empty sequence.
For details of the language
,
calendar
, and country
arguments,
see 16.5.2 The Language,
Calendar, and Country Arguments.
In general, the use of an invalid picture
,
language
, calendar
, or
country
argument is classified as a
non-recoverable dynamic
error. By contrast, use of an option in any of
these arguments that is valid but not supported by the
implementation is not an error, and in these cases the
implementation is required to output the value in a
fallback representation.
The picture consists of a sequence of variable markers and literal substrings. A substring enclosed in square brackets is interpreted as a variable marker; substrings not enclosed in square brackets are taken as literal substrings. The literal substrings are optional and if present are rendered unchanged, including any whitespace. If an opening or closing square bracket is required within a literal substring, it must be doubled. The variable markers are replaced in the result by strings representing aspects of the date and/or time to be formatted. These are described in detail below.
A variable marker consists of a component specifier followed optionally by one or two presentation modifiers and/or optionally by a width modifier. Whitespace within a variable marker is ignored.
The component specifier indicates the component of the date or time that is required, and takes the following values:
| Specifier | Meaning | Default Presentation Modifier |
|---|---|---|
| Y | year (absolute value) | 1 |
| M | month in year | 1 |
| D | day in month | 1 |
| d | day in year | 1 |
| F | day of week | n |
| W | week in year | 1 |
| w | week in month | 1 |
| H | hour in day (24 hours) | 1 |
| h | hour in half-day (12 hours) | 1 |
| P | am/pm marker | n |
| m | minute in hour | 01 |
| s | second in minute | 01 |
| f | fractional seconds | 1 |
| Z | timezone as a time offset from UTC, or if an alphabetic modifier is present the conventional name of a timezone (such as PST) | 1 |
| z | timezone as a time offset using GMT, for example GMT+1 | 1 |
| C | calendar: the name or abbreviation of a calendar name | n |
| E | era: the name of a baseline for the numbering of years, for example the reign of a monarch | n |
[ERR XTDE1340] It is a non-recoverable dynamic error if the syntax of the picture is incorrect.
[ERR XTDE1350] It is a non-recoverable dynamic
error if a component specifier within the picture
refers to components that are not available in the given
type of $value
, for example if the picture
supplied to the format-time
refers to the year, month, or day component.
It is not an error to include a timezone component when the supplied value has no timezone. In these circumstances the timezone component will be ignored.
The first presentation modifier indicates the style in which the value of a component is to be represented. Its value may be either:
any format token permitted in the
format
string of the xsl:number
instruction (see 12
Numbering), indicating that the value of the
component is to be output numerically using the
specified number format (for example, 1
,
01
, i
, I
,
w
, W
, or Ww
)
or
the format token n
, N
,
or Nn
, indicating that the value of the
component is to be output by name, in lower-case,
upper-case, or title-case respectively. Components
that can be output by name include (but are not
limited to) months, days of the week, timezones, and
eras. If the processor cannot output these components
by name for the chosen calendar and language then it
must use an implementation-defined fallback
representation.
If the implementation does not support the use of the requested format token, it must use the default presentation modifier for that component.
If the first presentation modifier is present, then it may optionally be followed by a second presentation modifier as follows:
| Modifier | Meaning |
|---|---|
| t | traditional numbering. This has
the same meaning as
letter-value="traditional" in xsl:number . |
| o | ordinal form of a number, for
example 8th or 8º . The
actual representation of the ordinal form of a
number may depend not only on the language, but
also on the grammatical context (for example, in
some languages it must agree in gender). |
Note:
Although the formatting rules are expressed in terms
of the rules for format tokens in xsl:number
, the
formats actually used may be specialized to the
numbering of date components where appropriate. For
example, in Italian, it is conventional to use an
ordinal number (primo
) for the first day
of the month, and cardinal numbers (due, tre,
quattro ...
) for the remaining days. A processor
may therefore use this convention to number days of the
month, ignoring the presence or absence of the ordinal
presentation modifier.
Whether or not a presentation modifier is included, a width modifier may be supplied. This indicates the number of characters or digits to be included in the representation of the value.
The width modifier, if present, is introduced by a comma. It takes the form:
, min-width ("-"
max-width)?
where min-width
is either an unsigned
integer indicating the minimum number of characters to be
output, or *
indicating that there is no
explicit minimum, and max-width
is either an
unsigned integer indicating the maximum number of
characters to be output, or *
indicating
that there is no explicit maximum; if
max-width
is omitted then *
is
assumed. Both integers, if present, must be greater than zero.
A format token containing leading zeroes, such as
001
, sets the minimum and maximum width to
the number of digits appearing in the format token; if a
width modifier is also present, then the width modifier
takes precedence.
Note:
A format token consisting of a one-digit on its own,
such as 1
, does not constrain the number
of digits in the output. In the case of fractional
seconds in particular, [f001]
requests
three decimal digits, [f01]
requests two
digits, but [f1]
will produce an
implementation-defined number of digits. If exactly one
digit is required, this can be achieved using the
component specifier [f1,1-1]
.
If the minumum and maximum width are unspecified, then the output uses as many characters as are required to represent the value of the component without truncation and without padding: this is referred to below as the full representation of the value.
If the full representation of the value exceeds the
specified maximum width, then the processor should attempt to use an alternative
shorter representation that fits within the maximum
width. Where the presentation modifier is N
,
n
, or Nn
, this is done by
abbreviating the name, using either conventional
abbreviations if available, or crude right-truncation if
not. For example, setting max-width
to
4
indicates that four-letter abbreviations
should be used, though it would
be acceptable to use a three-letter abbreviation if this
is in conventional use. (For example, "Tuesday" might be
abbreviated to "Tues", and "Friday" to "Fri".) In the
case of the year component, setting
max-width
requests omission of high-order
digits from the year, for example, if
max-width
is set to 2
then the
year 2003 will be output as 03
. In the
case of the fractional seconds component, the value is
rounded to the specified size as if by applying the
function round-half-to-even(fractional-seconds,
max-width)
. If no mechanism is available
for fitting the value within the specified maximum width
(for example, when roman numerals are used), then the
value should be output in its
full representation.
If the full representation of the value is shorter than the specified minimum width, then the processor should pad the value to the specified width. For decimal representations of numbers, this should be done by prepending zero digits from the appropriate set of digit characters, or appending zero digits in the case of the fractional seconds component. In other cases, it should be done by appending spaces.
The set of languages, calendars, and countries that are supported in the date formatting functions is implementation-defined. When any of these arguments is omitted or is an empty sequence, an implementation-defined default value is used.
If the fallback representation uses a different
calendar from that requested, the output string
must be prefixed with
[Calendar: X]
where X
identifies the calendar actually used. The string
Calendar
should be
localized using the requested language if available. If
the fallback representation uses a different language
from that requested, the output string should be prefixed
with [Language: Y]
where Y
identifies the language actually used. The string
Language
may be
localized in an implementation-dependent
way. If a particular component of the value cannot be
output in the requested format, it should be output in the default format for
that component.
The language
argument specifies the
language to be used for the result string of the
function. The value of the argument must be either the empty sequence or a
value that would be valid for the xml:lang
attribute (see [XML]). Note that this permits the
identification of sublanguages based on country codes
(from [ISO 3166-1]) as well as
identification of dialects and of regions within a
country.
If the language
argument is omitted or is
set to an empty sequence, or if it is set to an invalid
value or a value that the implementation does not
recognize, then the processor uses an implementation-defined
language.
The language is used to select the appropriate language-dependent forms of:
names (for example, of months)
numbers expressed as words or as ordinals (twenty, 20th, twentieth
)
hour convention (0-23 vs 1-24, 0-11 vs 1-12)
first day of week, first week of year
Where appropriate this choice may also take into
account the value of the country
argument,
though this should not be used
to override the language or any sublanguage that is
specified as part of the language
argument.
The choice of the names and abbreviations used in any
given language is implementation-defined.
For example, one implementation might abbreviate July as
Jul
while another uses Jly
. In
German, one implementation might represent Saturday as
Samstag
while another uses
Sonnabend
. Implementations may provide mechanisms allowing users to
control such choices.
Where ordinal numbers are used, the selection of the correct representation of the ordinal (for example, the linguistic gender) may depend on the component being formatted and on its textual context in the picture string.
The calendar
attribute specifies that the
dateTime
, date
, or
time
supplied in the $value
argument must be converted to a
value in the specified calendar and then converted to a
string using the conventions of that calendar.
A calendar value must be a valid QName. If the QName does not have a prefix, then it identifies a calendar with the designator specified below. If the QName has a prefix, then the QName is expanded into an expanded-QName as described in 5.1 Qualified Names; the expanded-QName identifies the calendar; the behavior in this case is implementation-defined.
If the calendar attribute is omitted an implementation-defined value is used.
Note:
The calendars listed below were known to be in use during the last hundred years. Many other calendars have been used in the past.
This specification does not define any of these
calendars, nor the way that they map to the value space
of the xs:date
data type in [XML Schema Part 2]. There may be
ambiguities when dates are recorded using different
calendars. For example, the start of a new day is not
simultaneous in different calendars, and may also vary
geographically (for example, based on the time of
sunrise or sunset). Translation of dates is therefore
more reliable when the time of day is also known, and
when the geographic location is known. When translating
dates between one calendar and another, the processor
may take account of the values of the
country
and/or language
arguments, with the country
argument
taking precedence.
Information about some of these calendars, and algorithms for converting between them, may be found in [Calendrical Calculations].
| Designator | Calendar |
|---|---|
| AD | Anno Domini (Christian Era) |
| AH | Anno Hegirae (Muhammedan Era) |
| AME | Mauludi Era (solar years since Mohammed's birth) |
| AM | Anno Mundi (Jewish Calendar) |
| AP | Anno Persici |
| AS | Aji Saka Era (Java) |
| BE | Buddhist Era |
| CB | Cooch Behar Era |
| CE | Common Era |
| CL | Chinese Lunar Era |
| CS | Chula Sakarat Era |
| EE | Ethiopian Era |
| FE | Fasli Era |
| ISO | ISO 8601 calendar |
| JE | Japanese Calendar |
| KE | Khalsa Era (Sikh calendar) |
| KY | Kali Yuga |
| ME | Malabar Era |
| MS | Monarchic Solar Era |
| NS | Nepal Samwat Era |
| OS | Old Style (Julian Calendar) |
| RS | Rattanakosin (Bangkok) Era |
| SE | Saka Era |
| SH | Mohammedan Solar Era (Iran) |
| SS | Saka Samvat |
| TE | Tripurabda Era |
| VE | Vikrama Era |
| VS | Vikrama Samvat Era |
At least one of the above calendars must be supported. It is implementation-defined which calendars are supported.
The ISO 8601 calendar ([ISO
8601]), which is included in the above list and
designated ISO
, is very similar to the
Gregorian calendar designated AD
, but it
differs in several ways. The ISO calendar is intended to
ensure that date and time formats can be read easily by
other software, as well as being legible for human users.
The ISO calendar prescribes the use of particular
numbering conventions as defined in ISO 8601, rather than
allowing these to be localized on a per-language basis.
In particular it provides a numeric 'week date' format
which identifies dates by year, week of the year, and day
in the week; in the ISO calendar the days of the week are
numbered from 1 (Monday) to 7 (Sunday), and week 1 in any
calendar year is the week (from Monday to Sunday) that
includes the first Thursday of that year. The numeric
values of the components year, month, day, hour, minute,
and second are the same in the ISO calendar as the values
used in the lexical representation of the date and time
as defined in [XML Schema Part
2]. The era ("E" component) with this calendar is
either a minus sign (for negative years) or a zero-length
string (for positive years). For dates before 1 January,
AD 1, year numbers in the ISO and AD calendars are off by
one from each other: ISO year 0000 is 1 BC, -0001 is 2
BC, etc.
Note:
The value space of the date and time data types, as
defined in XML Schema, is based on absolute points in
time. The lexical space of these data types defines a
representation of these absolute points in time using
the proleptic Gregorian calendar, that is, the modern
Western calendar extrapolated into the past and the
future; but the value space is calendar-neutral. The
date formatting
functions produce a representation of this absolute
point in time, but denoted in a possibly different
calendar. So, for example, the date whose lexical
representation in XML Schema is 1502-01-11
(the day on which Pope Gregory XIII was born) might be
formatted using the Old Style (Julian) calendar as
1 January 1502
. This reflects the fact
that there was at that time a ten-day difference
between the two calendars. It would be incorrect, and
would produce incorrect results, to represent this date
in an element or attribute of type xs:date
as 1502-01-01
, even though this might
reflect the way the date was recorded in contemporary
documents.
When referring to years occurring in antiquity,
modern historians generally use a numbering system in
which there is no year zero (the year before 1 CE is
thus 1 BCE). This is the convention that should be used when the requested
calendar is OS (Julian) or AD (Gregorian). When the
requested calendar is ISO, however, the conventions of
ISO 8601 should be followed:
here the year before +0001 is numbered zero. In
[XML Schema Part 2] (version
1.0), the value space for xs:date
and
xs:dateTime
does not include a year zero:
however, a future edition is expected to endorse the
ISO 8601 convention. This means that the date on which
Julius Caesar was assassinated has the ISO 8601 lexical
representation -0043-03-13, but will be formatted as 15
March 44 BCE in the Julian calendar or 13 March 44 BCE
in the Gregorian calendar (dependant on the chosen
localization of the names of months and eras).
The intended use of the country
argument
is to identify the place where an event represented by
the dateTime
, date
, or
time
supplied in the $value
argument took place or will take place. If the value is
supplied, and is not the empty sequence, then it
should be a country code
defined in [ISO 3166-1].
Implementations may also allow
the use of codes representing subdivisions of a country
from ISO 3166-2, or codes representing formerly used
names of countries from ISO 3166-3. This argument is not
intended to identify the location of the user for whom
the date or time is being formatted; that should be done
by means of the language
attribute. This
information may be used to
provide additional information when converting dates
between calendars or when deciding how individual
components of the date and time are to be formatted. For
example, different countries using the Old Style (Julian)
calendar started the new year on different days, and some
countries used variants of the calendar that were out of
synchronization as a result of differences in calculating
leap years. The geographical area identified by a
country code is defined by the boundaries as they existed
at the time of the date to be formatted, or the
present-day boundaries for dates in the
future.
The following examples show a selection of dates and times and the way they might be formatted. These examples assume the use of the Gregorian calendar as the default calendar.
| Required Output | Expression |
|---|---|
2002-12-31 |
format-date($d,
"[Y0001]-[M01]-[D01]") |
12-31-2002 |
format-date($d,
"[M]-[D]-[Y]") |
31-12-2002 |
format-date($d,
"[D]-[M]-[Y]") |
31 XII 2002 |
format-date($d, "[D1] [MI]
[Y]") |
31st December, 2002 |
format-date($d, "[D1o] [MNn], [Y]",
"en", (), ()) |
31 DEC 2002 |
format-date($d, "[D01] [MN,*-3]
[Y0001]", "en", (), ()) |
December 31, 2002 |
format-date($d, "[MNn] [D], [Y]", "en",
(), ()) |
31 Dezember, 2002 |
format-date($d, "[D] [MNn], [Y]", "de",
(), ()) |
Tisdag 31 December 2002 |
format-date($d, "[FNn] [D] [MNn] [Y]",
"sv", (), ()) |
[2002-12-31] |
format-date($d,
"[[[Y0001]-[M01]-[D01]]]") |
Two Thousand and Three |
format-date($d, "[YWw]", "en", (),
()) |
einunddreißigste Dezember |
format-date($d, "[Dwo] [MNn]", "de",
(), ()) |
3:58 PM |
format-time($t, "[h]:[m01] [PN]", "en",
(), ()) |
3:58:45 pm |
format-time($t, "[h]:[m01]:[s01] [Pn]",
"en", (), ()) |
3:58:45 PM PDT |
format-time($t, "[h]:[m01]:[s01] [PN]
[ZN,*-3]", "en", (), ()) |
3:58:45 o'clock PM PDT |
format-time($t, "[h]:[m01]:[s01]
o'clock [PN] [ZN,*-3]", "en") |
15:58 |
format-time($t,"[H01]:[m01]") |
15:58:45.762 |
format-time($t,"[H01]:[m01]:[s01].[f001]") |
15:58:45 GMT+02:00 |
format-time($t,"[H01]:[m01]:[s01] [z]",
"en", (), ()) |
15.58 Uhr GMT+02:00 |
format-time($t,"[H01]:[m01] Uhr [z]",
"de", (), ()) |
3.58pm on Tuesday, 31st
December |
format-dateTime($dt, "[h].[m01][Pn] on
[FNn], [D1o] [MNn]") |
12/31/2002 at
15:58:45 |
format-dateTime($dt,
"[M01]/[D01]/[Y0001] at
[H01]:[m01]:[s01]") |
The following examples use calendars other than the Gregorian calendar.
These examples use non-Latin characters which might not display correctly in all browsers, depending on the system configuration.
| Description | Request | Result |
|---|---|---|
| Islamic | format-date($d,
"[D١] [Mn] [Y١]",
"Islamic", "ar", "AH", ()) |
٢٦ ﺸﻭّﺍﻝ ١٤٢٣ |
| Jewish (with Western numbering) | format-date($d, "[D] [Mn]
[Y]", "he", "AM", ()) |
26 טבת 5763 |
| Jewish (with traditional numbering) | format-date($d,
"[Dאt] [Mn] [Yאt]", "he",
"AM", ()) |
כ״ו טבת תשס״ג |
| Julian (Old Style) | format-date($d, "[D] [MNn]
[Y]", "en", "OS", ()) |
18 December 2002 |
| Thai | format-date($d,
"[D๑] [Mn] [Y๑]", "th",
"BE", ()) |
๓๑ ธันวาคม ๒๕๔๕ |
current
() as
item()
The current
function,
used within an XPath expression, returns the item that
was the context item at the point where
the expression was invoked from the XSLT stylesheet. This
is referred to as the current item. For an outermost
expression (an expression not occurring within another
expression), the current item is always the same as the
context item. Thus,
<xsl:value-of select="current()"/>
means the same as
<xsl:value-of select="."/>
However, within square brackets, or on the right-hand
side of the /
operator, the current item is
generally different from the context item.
For example,
<xsl:apply-templates select="//glossary/entry[@name=current()/@ref]"/>
will process all entry
elements that
have a glossary
parent element and that
have a name
attribute with value equal to
the value of the current item's ref
attribute. This is different from
<xsl:apply-templates select="//glossary/entry[@name=./@ref]"/>
which means the same as
<xsl:apply-templates select="//glossary/entry[@name=@ref]"/>
and so would process all entry
elements
that have a glossary
parent element and
that have a name
attribute and a
ref
attribute with the same value.
If the current
function is
used within a pattern, its value is the node that is
being matched against the pattern.
[ERR XTDE1360] If the current
function is
evaluated within an expression that is evaluated when the
context item is undefined, a non-recoverable dynamic
error occurs.
unparsed-entity-uri
($entity-name
as
xs:string
) as
xs:anyURI
The unparsed-entity-uri
function returns the URI of the unparsed entity whose
name is given by the value of the
$entity-name
argument, in the document
containing the context node. It returns the
zero-length xs:anyURI
if there
is no such entity. This function maps to the
dm:unparsed-entity-system-id
accessor
defined in [Data
Model].
[ERR XTDE1370] It is a non-recoverable dynamic
error if the unparsed-entity-uri
function is called when there is no context node,
or when the root of the tree containing the context node
is not a document node.
unparsed-entity-public-id
(
$entity-name
as
xs:string
) as
xs:string
The unparsed-entity-public-id
function returns the public identifier of the unparsed
entity whose name is given by the value of the
$entity-name
argument, in the document
containing the context node. It returns the
zero-length string if there is no such entity, or
if the entity has no public identifier. This
function maps to the
dm:unparsed-entity-public-id
accessor
defined in [Data
Model].
[ERR XTDE1380] It is a non-recoverable dynamic
error if the unparsed-entity-public-id
function is called when there is no context node,
or when the root of the tree containing the context node
is not a document node.
generate-id
() as
xs:string
generate-id
($node
as
node()?
) as
xs:string
The generate-id
function returns a string that uniquely identifies a
given node. The unique identifier must consist of ASCII alphanumeric
characters and must start with
an alphabetic character. Thus, the string is
syntactically an XML name. An implementation is free to
generate an identifier in any convenient way provided
that it always generates the same identifier for the same
node and that different identifiers are always generated
from different nodes. An implementation is under no
obligation to generate the same identifiers each time a
document is transformed. There is no guarantee that a
generated unique identifier will be distinct from any
unique IDs specified in the source document. If the
argument is the empty sequence, the result is the
zero-length string. If the argument is
omitted, it defaults to the context node.
system-property
($property-name
as
xs:string
) as
xs:string
The $property-name
argument must evaluate to a lexical QName. The lexical
QName is expanded as described in 5.1 Qualified Names.
[ERR XTDE1390] It is a non-recoverable dynamic error if the value is not a valid QName, or if there is no namespace declaration in scope for the prefix of the QName. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.
The system-property
function returns a string representing the value of the
system property identified by the name. If there is no
such system property, the zero-length string
is returned.
Implementations must provide the following system properties, which are all in the XSLT namespace:
xsl:version
, a number giving the
version of XSLT implemented by the processor; for
implementations conforming to the version of XSLT
specified by this document, this is the string
"2.0"
. The value will always be a string
in the lexical space of the decimal data type defined
in XML Schema (see [XML Schema
Part 2]). This allows the value to be converted
to a number for the purpose of magnitude
comparisons.
xsl:vendor
, a string identifying the
implementer of the processor
xsl:vendor-url
, a string containing a
URL identifying the implementer of the processor;
typically this is the host page (home page) of the
implementer's Web site.
xsl:product-name
, a string containing
the name of the implementation, as defined by the
implementer. This should
normally remain constant from one release of the
product to the next. It should also be constant across
platforms in cases where the same source code is used
to produce compatible products for multiple execution
platforms.
xsl:product-version
, a string
identifying the version of the implementation, as
defined by the implementer. This should normally vary from one release
of the product to the next, and at the discretion of
the implementer it may also
vary across different execution platforms.
xsl:is-schema-aware
, returns the
string "yes"
in the case of a processor
that claims conformance as a schema-aware XSLT
processor, or "no"
in the case of a
basic XSLT
processor.
xsl:supports-serialization
, returns
the string "yes"
in the case of a
processor that offers the serialization
feature, or "no"
otherwise.
xsl:supports-backwards-compatibility
,
returns the string "yes"
in the case of
a processor that offers the backwards
compatibility feature, or "no"
otherwise.
Some of these properties relate to the conformance levels and features offered by the processor: these options are described in 21 Conformance.
The actual values returned for the above properties are implementation-defined.
The set of system properties that are supported, in addition to those listed above, is also implementation-defined. Implementations must not define additional system properties in the XSLT namespace.
Note:
An implementation must not return the value
2.0
as the value of the
xsl:version
system property unless it is
conformant to XSLT 2.0.
It is recognized that vendors who are enhancing XSLT
1.0 processors may wish to release interim
implementations before all the mandatory features of
this specification are implemented. Since such products
are not conformant to XSLT 2.0, this specification
cannot define their behavior. However, implementers of
such products are encouraged to return a value for the
xsl:version
system property that is
intermediate between 1.0 and 2.0, and to provide the
element-available
and function-available
functions to allow users to test which features have
been fully implemented.

<xsl:message
select? = expression
terminate? = { "yes" | "no" }>

</xsl:message>
The xsl:message
instruction
sends a message in an implementation-defined way.
The xsl:message
instruction causes the creation of a new document, which is
typically serialized and output to an implementation-defined
destination. The result of the xsl:message
instruction
is an empty sequence.
The content of the message may be specified by using
either or both of the optional select
attribute
and the sequence constructor that
forms the content of the xsl:message
instruction.
If the xsl:message
instruction
contains a sequence constructor, then the
sequence obtained by evaluating this sequence constructor is
used to construct the content of the new document node, as
described in 5.7.1
Constructing Complex Content.
If the xsl:message
instruction
has a select
attribute, then the value of the
attribute must be an XPath
expression. The effect of the xsl:message
instruction
is then the same as if a single xsl:copy-of
instruction
with this select
attribute were added to the
start of the sequence constructor.
If the xsl:message
instruction
has no content and no select
attribute, then an
empty message is produced.
The tree produced by the xsl:message
instruction
is not technically a final result tree. The tree has
no URI and processors are not required to make the tree accessible to
applications.
Note:
In many cases, the XML document produced using xsl:message
will
consist of a document node owning a single text node.
However, it may contain a more complex structure.
Note:
An implementation might implement xsl:message
by popping
up an alert box or by writing to a log file. Because
the order of execution of instructions is
implementation-defined, the order in which such messages
appear is not predictable.
The terminate
attribute is interpreted as an
attribute value
template.
If the effective value of the
terminate
attribute is yes
, then
the processor
must terminate processing after
sending the message. The default value is no
.
Note that because the order of evaluation of instructions is
implementation-dependent,
this gives no guarantee that any particular instruction will
or will not be evaluated before processing terminates.
[ERR XTMM9000] When a transformation is
terminated by use of xsl:message
terminate="yes"
, the effect is the same as when a
non-recoverable dynamic error
occurs during the transformation.
One convenient way to do localization is to put the
localized information (message text, etc.) in an XML
document, which becomes an additional input file to the
stylesheet.
For example, suppose messages for a language
L
are stored in an XML file
resources/L.xml
in the form:
<messages> <message name="problem">A problem was detected.</message> <message name="error">An error was detected.</message> </messages>
Then a stylesheet could use the following approach to localize messages:
<xsl:param name="lang" select="'en'"/> <xsl:variable name="messages" select="document(concat('resources/', $lang, '.xml'))/messages"/> <xsl:template name="localized-message"> <xsl:param name="name"/> <xsl:message select="string($messages/message[@name=$name])"/> </xsl:template> <xsl:template name="problem"> <xsl:call-template name="localized-message"> <xsl:with-param name="name">problem</xsl:with-param> </xsl:call-template> </xsl:template>
XSLT allows two kinds of extension, extension instructions and extension functions.
[Definition: An extension instruction is an element within a sequence constructor that is in a namespace (not the XSLT namespace) designated as an extension namespace.]
[Definition: An extension function is a
function that is available for use within an XPath expression, other than
a core
function defined in [Functions
and Operators], an additional function defined in this
XSLT specification, a constructor function named after
an atomic type, or a stylesheet function
defined using an xsl:function
declaration.].
This specification does not define any mechanism for creating or binding implementations of extension instructions or extension functions, and it is not required that implementations support any such mechanism. Such mechanisms, if they exist, are implementation-defined. Therefore, an XSLT stylesheet that must be portable between XSLT implementations cannot rely on particular extensions being available. XSLT provides mechanisms that allow an XSLT stylesheet to determine whether the implementation makes particular extensions available, and to specify what happens if those extensions are not available. If an XSLT stylesheet is careful to make use of these mechanisms, it is possible for it to take advantage of extensions and still retain portability.
The set of functions that can be called from a FunctionCall XP within an XPath expression may include one or more extension functions. The expanded-QName of an extension function always has a non-null namespace URI.
The function-available
function can be used with the [xsl:]use-when
attribute (see 3.12
Conditional Element Inclusion) to explicitly
control how a stylesheet behaves if a particular
extension function is not available.
function-available
($function-name
as
xs:string
) as
xs:boolean
function-available ( |
$function-name |
as xs:string , |
$arity |
as xs:integer ) as xs:boolean |
A function is said to be available within an XPath expression if it is present in the in-scope functionsXP for that expression (see 5.4.1 Initializing the Static Context). Functions in the static context are uniquely identified by the name of the function (a QName) in combination with its arity.
The value of the $function-name
argument
must be a string containing a
lexical
QName. The lexical QName is expanded into an
expanded-QName using the
namespace declarations in scope for the expression. If the
lexical QName is unprefixed, then the standard function
namespace is used in the expanded QName.
The two-argument version of the function-available
function returns true if and only if there is an
available function whose name matches the value of the
$function-name
argument and whose arity matches the value of
the $arity
argument.
The single-argument version of the function-available
function returns true if and only if there is at least
one available function (with some arity) whose name
matches the value of the $function-name
argument.
[ERR XTDE1400] It is a non-recoverable dynamic error if the argument does not evaluate to a string that is a valid QName, or if there is no namespace declaration in scope for the prefix of the QName. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.
When backwards compatible
behavior is enabled, the function-available
function returns false in respect of a function name and
arity for which no implementation is available (other
than the fallback error function that raises a dynamic
error whenever it is called). This means that it is
possible (as in XSLT 1.0) to use logic such as the
following to test whether a function is available before
calling it:
 <xsl:choose> <xsl:when test="function-available('my:summary')"> <xsl:value-of select="my:summary()"/> </xsl:when> <xsl:otherwise> <xsl:text>Summary not available</xsl:text> </xsl:otherwise> </xsl:choose>
Note:
The fact that a function with a given name is available gives no guarantee that any particular call on the function will be successful. For example, it is not possible to determine the types of the arguments expected.
Note:
In XSLT 2.0 (without backwards compatibility
enabled) a static error occurs when an XPath
expression references a function that is not available.
This is true even in a part of the stylesheet that uses
forwards-compatible
behavior. Therefore, the conditional logic to test
whether a function is available before calling it
should normally be written in a use-when
attribute (see 3.12
Conditional Element Inclusion).
A stylesheet that is designed to use XSLT 2.0 facilities when they are available, but to fall back to XSLT 1.0 capabilities when not, might be written using the code:
<out xsl:version="2.0"> <xsl:choose> <xsl:when test="function-available('matches')"> <xsl:value-of select="matches($input, '[a-z]*')"/> </xsl:when> <xsl:otherwise> <xsl:value-of select="string-length( translate($in, 'abcdefghijklmnopqrstuvwxyz', '')) = 0"/> </xsl:otherwise> </xsl:choose> </out>
Here an XSLT 2.0 processor will always take the
xsl:when
branch, while a 1.0 processor will follow the xsl:otherwise
branch. The single-argument version of the function-available
function is used here, because that is the only version
available in XSLT 1.0. Under the rules of XSLT 1.0, the
call on the matches
function is not an
error, because it is never evaluated.
A stylesheet that is designed to use facilities in
some future XSLT version when they are available, but
to fall back to XSLT 2.0 capabilities when not, might
be written using code such as the following. This
hypothesizes the availability in some future version of
a function pad
which pads a string to a
fixed length with spaces:
<xsl:value-of select="pad($input, 10)" use-when="function-available('pad', 2)"/> <xsl:value-of select="concat($input, string-join( for $i in 1 to 10 - string-length($input) return ' ', ''))" use-when="not(function-available('pad', 2))"/>
In this case the two-argument version of function-available
is used, because there is no requirement for this code
to run under XSLT 1.0.
If the function name used in a FunctionCall XP within an XPath expression identifies an extension function, then to evaluate the FunctionCall XP, the processor will first evaluate each of the arguments in the FunctionCall XP. If the processor has information about the data types expected by the extension function, then it may perform any necessary type conversions between the XPath data types and those defined by the implementation language. If multiple extension functions are available with the same name, the processor may decide which one to invoke based on the number of arguments, the types of the arguments, or any other criteria. The result returned by the implementation is returned as the result of the function call, again after any necessary conversions between the data types of the implementation language and those of XPath. The details of such type conversions are outside the scope of this specification.
[ERR XTDE1420] It is a non-recoverable dynamic error if the arguments supplied to a call on an extension function do not satisfy the rules defined for that particular extension function, or if the extension function reports an error, or if the result of the extension function cannot be converted to an XPath value.
Note:
Implementations may also provide mechanisms allowing extension functions to report recoverable dynamic errors, or to execute within an environment that treats some or all of the errors listed above as recoverable.
[ERR XTDE1425] When backwards compatible behavior is enabled, it is a non-recoverable dynamic error to evaluate an extension function call if no implementation of the extension function is available.
Note:
When backwards-compatible behavior is not enabled, this is a static error [XPST0017].
Note:
There is no prohibition on calling extension functions that have side-effects (for example, an extension function that writes data to a file). However, the order of execution of XSLT instructions is not defined in this specification, so the effects of such functions are unpredictable.
Implementations are not required to perform full validation of values returned by extension functions. It is an error for an extension function to return a string containing characters that are not permitted in XML, but the consequences of this error are implementation-defined. The implementation may raise an error, may convert the string to a string containing valid characters only, or may treat the invalid characters as if they were permitted characters.
Note:
The ability to execute extension functions represents a potential security weakness, since untrusted stylesheets may invoke code that has privileged access to resources on the machine where the processor executes. Implementations may therefore provide mechanisms that restrict the use of extension functions by untrusted stylesheets.
All observations in this section regarding the errors that can occur when invoking extension functions apply equally when invoking extension instructions.
An implementation may allow
an extension function to return an object that does not
have any natural representation in the XDM
data model, either as an atomic value or as a node. For
example, an extension function sql:connect
might return an object that represents a connection to a
relational database; the resulting connection object
might be passed as an argument to calls on other
extension functions such as sql:insert
and
sql:select
.
The way in which such objects are represented in the
type system is implementation-defined.
They might be represented by a completely new data type,
or they might be mapped to existing data types such as
integer
, string
, or
anyURI
.
The type-available
function can be used, for example with the
[xsl:]use-when
attribute (see 3.12 Conditional Element
Inclusion), to explicitly control how a
stylesheet behaves if a particular schema type is not
available in the static context.
type-available
($type-name
as
xs:string
) as
xs:boolean
A schema type (that is, a simple type or a complex
type) is said to be available within an XPath expression
if it is a type definition that is present in the
in-scope
schema typesXP for that
expression (see 5.4.1
Initializing the Static Context). This includes
built-in types, types imported using xsl:import-schema
,
and extension types defined by the implementation.
The value of the $type-name
argument
must be a string containing a
lexical
QName. The lexical QName is expanded into an
expanded-QName using the
namespace declarations in scope for the expression. If the
lexical QName is unprefixed, then the default namespace
is used in the expanded QName.
The function returns true if and only if there is an
available type whose name matches the value of the
$type-name
argument.
[ERR XTDE1428] It is a non-recoverable dynamic error if the argument does not evaluate to a string that is a valid QName, or if there is no namespace declaration in scope for the prefix of the QName. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.
[Definition: The extension instruction mechanism allows namespaces to be designated as extension namespaces. When a namespace is designated as an extension namespace and an element with a name from that namespace occurs in a sequence constructor, then the element is treated as an instruction rather than as a literal result element.] The namespace determines the semantics of the instruction.
Note:
Since an element that is a child of an xsl:stylesheet
element is not occurring in a sequence constructor,
user-defined data elements (see
3.6.2 User-defined
Data Elements) are not extension elements as
defined here, and nothing in this section applies to
them.
A namespace is designated as an extension namespace by
using an [xsl:]extension-element-prefixes
attribute on an element in the stylesheet (see 3.5 Standard
Attributes). The attribute must be in the XSLT namespace only if its
parent element is not in the XSLT namespace. The
value of the attribute is a whitespace-separated list of
namespace prefixes. The namespace bound to each of the
prefixes is designated as an extension namespace.
The default namespace (as declared by
xmlns
) may be designated as an extension
namespace by including #default
in the list
of namespace prefixes.
[ERR XTSE1430] It is a static error
if there is no namespace bound to the prefix on the
element bearing the
[xsl:]extension-element-prefixes
attribute
or, when #default
is specified, if
there is no default namespace.
The designation of a namespace as an extension
namespace is effective for the element bearing the
[xsl:]extension-element-prefixes
attribute
and for all descendants of that element within the same
stylesheet module.
The element-available
function can be used with the xsl:choose
and
xsl:if
instructions, or with the
[xsl:]use-when
attribute (see 3.12 Conditional Element
Inclusion) to explicitly control how a stylesheet
behaves when a particular XSLT instruction or extension
instruction is (or is not) available.
element-available
($element-name
as
xs:string
) as
xs:boolean
The value of the $element-name
argument
must be a string containing a
QName. The
QName is expanded
into an expanded-QName using the
namespace declarations in scope for the expression. If
there is a default namespace in scope, then it is used to
expand an unprefixed QName. The element-available
function returns true if and only if the expanded-QName is the name of an
instruction. If the expanded-QName has a namespace
URI equal to the XSLT namespace URI, then it
refers to an element defined by XSLT. Otherwise, it
refers to an extension instruction. If
the expanded-QName has a null
namespace URI, the element-available
function will return false.
[ERR XTDE1440] It is a non-recoverable dynamic error if the argument does not evaluate to a string that is a valid QName, or if there is no namespace declaration in scope for the prefix of the QName. If the processor is able to detect the error statically (for example, when the argument is supplied as a string literal), then the processor may optionally signal this as a static error.
If the expanded-QName is in the XSLT namespace, the function returns true if and only if the expanded QName is the name of an XSLT instruction, that is, an XSLT element whose syntax summary in this specification classifies it as an instruction.
Note:
Although the result of applying this function to a name in the XSLT namespace when using a conformant XSLT 2.0 processor is entirely predictable, the function is useful in cases where the stylesheet might be executing under a processor that implements some other version of XSLT with different rules.
If the expanded-QName is not in the XSLT namespace, the function returns true if and only if the processor has an implementation available of an extension instruction with the given expanded QName. This applies whether or not the namespace has been designated as an extension namespace.
If the processor does not have an implementation of a particular extension instruction available, and such an extension instruction is evaluated, then the processor must perform fallback for the element as specified in 18.2.3 Fallback. An implementation must not signal an error merely because the stylesheet contains an extension instruction for which no implementation is available.

<xsl:fallback>

</xsl:fallback>
The content of an xsl:fallback
element
is a sequence constructor, and
when performing fallback, the value returned by the
xsl:fallback
element is the result of evaluating this sequence
constructor.
When not performing fallback, evaluating an xsl:fallback
element
returns an empty sequence: the content of the xsl:fallback
element
is ignored.
There are two situations where a processor performs fallback: when an extension instruction that is not available is evaluated, and when an instruction in the XSLT namespace, that is not defined in XSLT 2.0, is evaluated within a region of the stylesheet for which forwards compatible behavior is enabled.
Note:
Fallback processing is not invoked in other
situations, for example it is not invoked when an XPath
expression uses unrecognized syntax or contains a call
to an unknown function. To handle such situations
dynamically, the stylesheet should call functions such
as system-property
and function-available
to decide what capabilities are available.
[ERR XTDE1450] When a processor performs
fallback for an extension instruction
that is not recognized, if the instruction element has
one or more xsl:fallback
children, then the content of each of the xsl:fallback
children must be evaluated; it
is a non-recoverable dynamic
error if it has no xsl:fallback
children.
Note:
This is different from the situation with
unrecognized XSLT elements. As explained in
3.9 Forwards-Compatible
Processing, an unrecognized XSLT element
appearing within a sequence
constructor is a static error unless (a) forwards-compatible
behavior is enabled, and (b) the instruction has an
xsl:fallback
child.
The output of a transformation is a set of one or more final result trees.
A final result tree can be created
explicitly, by evaluating an xsl:result-document
instruction. As explained in 2.4 Executing a
Transformation, a final result tree is also
created implicitly if no xsl:result-document
instruction is evaluated, or if the result of evaluating the
initial template is a non-empty
sequence.
The way in which a final result tree is delivered to an application is implementation-defined.
Serialization of final result trees is described further in 20 Serialization

<xsl:result-document
format? = { qname }
href? = { uri-reference }
validation? = "strict" | "lax" | "preserve" |
"strip"
type? = qname
method? = { "xml" | "html" | "xhtml" | "text" |
qname-but-not-ncname }
byte-order-mark? = { "yes" | "no" }
cdata-section-elements? = { qnames
}
doctype-public? = { string }
doctype-system? = { string }
encoding? = { string }
escape-uri-attributes? = { "yes" | "no" }
include-content-type? = { "yes" | "no" }
indent? = { "yes" | "no" }
media-type? = { string }
normalization-form? = { "NFC" | "NFD" | "NFKC"
| "NFKD" | "fully-normalized" | "none" | nmtoken
}
omit-xml-declaration? = { "yes" | "no" }
standalone? = { "yes" | "no" | "omit" }
undeclare-prefixes? = { "yes" | "no" }
use-character-maps? = qnames
output-version? = { nmtoken
}>

</xsl:result-document>
The xsl:result-document
instruction is used to create a final
result tree. The content of the xsl:result-document
element is a sequence constructor for the
children of the document node of the tree. A document node
is created, and the sequence obtained by evaluating the
sequence constructor is used to construct the content of
the document, as described in 5.7.1 Constructing
Complex Content. The tree rooted at this document
node forms the final result tree.
The xsl:result-document
instruction defines the URI of the result tree, and may