Copyright © 1999 W3C (MIT, INRIA, Keio), All Rights Reserved. W3C liability, trademark, document use and software licensing rules apply.
XSLT is a language for transforming XML documents into other XML documents.
XSLT is designed for use as part of XSL, which is a stylesheet language for XML. In addition to XSLT, XSL includes an XML vocabulary for specifying formatting. XSL specifies the styling of an XML document by using XSLT to describe how the document is transformed into another XML document that uses the formatting vocabulary.
XSLT is also designed to be used independently of XSL. However, XSLT is not intended as a completely general-purpose XML transformation language. Rather it is designed primarily for the kinds of transformation that are needed when XSLT is used as part of XSL.
This is a W3C Working Draft for review by W3C members and other interested parties. The XSL Working Group considers that this draft is stable and ready to move to Proposed Recommendation status. This is therefore the last call for comments on this Working Draft. Please send detailed comments to xsl-editors@w3.org before 2 September 1999; archives of the comments are available.
This is a draft document and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use W3C Working Drafts as reference material or to cite them as other than "work in progress". A list of current W3C working drafts can be found at http://www.w3.org/TR.
This is part of the Style activity.
The English version of this specification is the only normative version. However, for translations of this document, see http://www.w3.org/Style/XSL/translations.html.
Public discussion of XSL, including XSL Transformations, takes place on the XSL-List mailing list.
A transformation expressed in XSLT describes rules for transforming a source tree into a result tree. The transformation is achieved by associating patterns with templates. A pattern is matched against elements in the source tree. A template is instantiated to create part of the result tree. The result tree is separate from the source tree. The structure of the result tree can be completely different from the structure of the source tree. In constructing the result tree, elements from the source tree can be filtered and reordered, and arbitrary structure can be added.
A transformation expressed in XSLT is called a stylesheet. This is because, in the case when XSLT is transforming into the XSL formatting vocabulary, the transformation functions as a stylesheet.
This document does not specify how an XSLT stylesheet is associated with an XML document. It is recommended that XSL processors support the mechanism described in [XML Stylesheet].
A stylesheet contains a set of template rules. A template rule has two parts: a pattern which is matched against nodes in the source tree and a template which can be instantiated to form part of the result tree. This allows a stylesheet to be applicable to a wide class of documents that have similar source tree structures.
A template is instantiated for a particular source element to create part of the result tree. A template can contain elements that specify literal result element structure. A template can also contain elements that are instructions for creating result tree fragments. When a template is instantiated, each instruction is executed and replaced by the result tree fragment that it creates. Instructions can select and process descendant source elements. Processing a descendant element creates a result tree fragment by finding the applicable template rule and instantiating its template. Note that elements are only processed when they have been selected by the execution of an instruction. The result tree is constructed by finding the template rule for the root node and instantiating its template.
In the process of finding the applicable template rule, more than one template rule may have a pattern that matches a given element. However, only one template rule will be applied. The method for deciding which template rule to apply is described in [5.5 Conflict Resolution for Template Rules].
A single template by itself has considerable power: it can create structures of arbitrary complexity; it can pull string values out of arbitrary locations in the source tree; it can generate structures that are repeated according to the occurrence of elements in the source tree. For simple transformations where the structure of the result tree is independent of the structure of the source tree, a stylesheet can often consist of only a single template, which functions as a template for the complete result tree. Transformations on XML documents that represent data are often of this kind (see [C.2 Data Example]). XSLT allows a simplified syntax for such stylesheets (see [2.3 Literal Result Element as Stylesheet]).
XSLT uses XML namespaces [XML Names] to distinguish
elements that are instructions to the XSLT processor from elements that
specify literal result tree structure. Instruction elements all
belong to the XSLT namespace. The examples in this document use a
prefix of xsl: for elements in the XSLT namespace.
XSLT makes use of the expression language defined by [XPath] for selecting elements for processing, for conditional processing and for generating text.
XSLT provides two "hooks" for extending the language, one hook for extending the set of instruction elements used in templates and one hook for extending the set of functions used in XPath expressions. These hooks are both based on XML namespaces. This version of XSLT does not define a mechanism for implementing the hooks. See [14 Extensions].
NOTE: The XSL WG intends to define such a mechanism in a future version of this specification or in a separate specification.
XSLT processors must use the XML namespaces mechanism [XML Names] to recognize XSLT-defined elements. All XSLT-defined
elements, that is those elements specified in this document with a
prefix of xsl:, will only be recognized by the XSLT
processor if they belong to a namespace with the URI
http://www.w3.org/XSL/Transform/1.0 (but see [2.5 Forwards-Compatible Processing]); XSLT-defined elements are recognized only in the
stylesheet not in the source document.
An element from the XSLT namespace may have any attribute not from the XSLT namespace, provided that the expanded name of the attribute has a non-null namespace URI. The presence of such attributes must not change the behavior of XSLT elements and functions defined in this document. Thus, an XSLT processor is always free to ignore such attributes, and must ignore such attributes without giving an error if it does not recognize the namespace URI. Such attributes can provide, for example, unique identifiers, optimization hints, or documentation.
It is an error for an element from the XSLT namespace to have attributes with expanded names that have null namespace URIs (i.e. attributes with unprefixed names) other than attributes defined for the element in this document.
NOTE: The conventions used for the names of XSLT elements, attributes and functions are that names are all lower-case, use hyphens to separate words, and use abbreviations only if they already appear in the syntax of a related language such as XML or HTML.
Ed. Note: For each xsl element, provide in addition to the prose explanation a prototypical element as a summary of what's allowed.
A stylesheet is represented by an xsl:stylesheet
element in an XML document. xsl:transform is allowed as
a synonym for xsl:stylesheet.
The xsl:stylesheet element may contain the following types
of elements:
xsl:import
xsl:include
xsl:strip-space
xsl:preserve-space
xsl:output
xsl:key
xsl:locale
xsl:attribute-set
xsl:variable
xsl:param
xsl:template
An element occurring as
a child of an xsl:stylesheet element is called a
top-level element.
This example shows the structure of a stylesheet. Ellipses
(...) indicate where attribute values or content have
been omitted. Although this example shows one of each type of allowed
element, stylesheets may contain zero or more of each of these
elements.
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0">
<xsl:import href="..."/>
<xsl:include href="..."/>
<xsl:strip-space elements="..."/>
<xsl:preserve-space elements="..."/>
<xsl:output method="..."/>
<xsl:key name="..." match="..." use="..."/>
<xsl:locale name="...">
...
</xsl:locale>
<xsl:attribute-set name="...">
...
</xsl:attribute-set>
<xsl:variable name="...">...</xsl:variable>
<xsl:param name="...">...</xsl:param>
<xsl:template match="...">
...
</xsl:template>
<xsl:template name="...">
...
</xsl:template>
</xsl:stylesheet>
The order in which the children of the xsl:stylesheet
element occur is not significant except for xsl:import
elements and for error recovery. Users are free to order the elements
as they prefer, and stylesheet creation tools need not provide control
over the order in which the elements occur.
In addition, the xsl:stylesheet element may contain
any element not from the XSLT namespace, provided that the expanded
name of the element has a non-null namespace URI. The presence of
such top-level elements must not change the behavior of XSLT elements
and functions defined in this document; for example, it would not be
permitted for such a top-level element to specify that
xsl:apply-templates was to use different rules to resolve
conflicts. Thus, an XSLT processor is always free to ignore such
top-level elements, and must ignore a top-level element without giving
an error if it does not recognize the namespace URI. Such elements can
provide, for example,
information used by extension elements or extension functions (see [14 Extensions]),
information about what to do with the result tree,
information about how to obtain the source tree,
structured documentation for the stylesheet.
A simplified syntax is allowed for stylesheets that consist of only
a single template for the root node. The stylesheet may consist of
just a literal result element (see [7.1.1 Literal Result Elements]). Such a stylesheet is equivalent to a
stylesheet with an xsl:stylesheet element containing a
template rule containing the literal result element; the template rule
has a match pattern of /. For example
<html xmlns:xsl="http://www.w3.org/XSL/Transform/1.0"
xmlns="http://www.w3.org/TR/xhtml1">
<head>
<title>Expense Report Summary</title>
</head>
<body>
<p>Total Amount: <xsl:value-of select="expense-report/total"/></p>
</body>
</html>
has the same meaning as
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0"
xmlns="http://www.w3.org/TR/xhtml1">
<xsl:template match="/">
<html>
<head>
<title>Expense Report Summary</title>
</head>
<body>
<p>Total Amount: <xsl:value-of select="expense-report/total"/></p>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
The allowed content of a literal result element when used as a stylesheet is no different than when it occurs within a stylesheet. Thus, a literal result element used as a stylesheet cannot contain top-level elements.
NOTE: The XSLT namespace need not be declared on the document element. Attributes on literal result elements that do not have a declaration of the XSLT namespace in scope are still treated as attribute value templates and quoted namespaces are still treated as usual (see [7.1.1 Literal Result Elements]).
The name of an internal XSLT object, specifically a named template (see [6 Named Templates]), a mode (see [5.7 Modes]), an attribute set (see [7.1.4 Named Attribute Sets]), a key (see [13.2 Keys]), a locale (see [13.3 Number Formatting]), a variable or a parameter (see [11 Variables and Parameters]) is specified as a QName. If it has a prefix, then the prefix is expanded into a URI reference using the namespace declarations in effect on the attribute in which the name occurs. The expanded name consisting of the local part of the name and the possibly null URI reference is used as the name of the object. The default namespace is not used for unprefixed names.
If the namespace URI of the expanded name of an element or
attribute starts with http://www.w3.org/XSL/Transform/
but is not equal to the XSLT 1.0 namespace URI
(http://www.w3.org/XSL/Transform/1.0), then an XSLT
processor must treat the element or attribute the same as if its
namespace URI was the XSLT 1.0 namespace URI, except that it must
recover from errors as follows:
if it is a top-level element and XSLT 1.0 does not allow such elements as top-level elements, then the element must be ignored along with its content;
if it is an element in a template and XSLT 1.0 does not allow such elements to occur in templates, then an error must not be signaled unless the element is actually instantiated;
if it is an element and the element has an attribute that XSLT 1.0 does not allow the element to have, then the attribute must be ignored;
if it is an attribute occurring on a literal result element, and XSLT 1.0 does not allow literal result elements to have such an attribute, then the attribute must be ignored.
Thus, any XSLT 1.0 processor must be able to process the following stylesheet without error, although the stylesheet is not a correct XSLT 1.0 stylesheet:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.1">
<xsl:template match="/">
<xsl:choose>
<xsl:when test="system-property('xsl:version') >= 1.1">
<xsl:exciting-new-1.1-feature/>
</xsl:when>
<xsl:otherwise>
<p>Sorry this stylesheet requires XSLT 1.1.</p>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
If an expression
occurs in an attribute value template in an attribute of a literal result element and the namespace URI of the expanded name of the nearest ancestor element that is not a literal result element is not the XSLT 1.0 namespace URI, or
occurs in an attribute on an XSLT element and the namespace URI of the expanded name of the element is not the XSLT 1.0 namespace URI,
then an XSLT processor must recover from errors in the expression as follows:
if the expression does not match the syntax allowed by the XPath grammar, then an error must not be signaled unless the expression is actually evaluated;
if the expression calls a function with an unprefixed name that is not part of the XSLT library, then an error must not be signaled unless the function is actually called.
XSLT provides two mechanisms to combine stylesheets:
An XSLT stylesheet may include another XSLT stylesheet using an
xsl:include element. The xsl:include element
has an href attribute whose value is a URI reference
identifying the stylesheet to be included. A relative URI is resolved
relative to the base URI of the xsl:include element (see
[3.2 Base URI]).
The xsl:include element is only allowed as a top-level element.
The inclusion works at the XML tree level. The resource located by
the href attribute value is parsed as an XML document,
and the children of the xsl:stylesheet element in this
document replace the xsl:include element in the including
document. The fact that template rules or definitions are included
does not affect the way they are processed.
The included stylesheet may use the simplified syntax described in
[2.3 Literal Result Element as Stylesheet]. The included stylesheet
is treated the same as the equivalent xsl:stylesheet
element.
It is an error if a stylesheet directly or indirectly includes itself.
An XSLT stylesheet may import another XSLT stylesheet using an
xsl:import element. Importing a stylesheet is the same
as including it (see [2.6.1 Stylesheet Inclusion]) except that definitions
and template rules in the importing stylesheet take precedence over
template rules and definitions in the imported stylesheet; this is
described in more detail below. The xsl:import element
has an href attribute whose value is a URI reference
identifying the stylesheet to be imported. A relative URI is resolved
relative to the base URI of the xsl:import element (see
[3.2 Base URI]).
The xsl:import element is only allowed as a top-level element. The
xsl:import element children must precede all other
element children of an xsl:stylesheet element, including
any xsl:include element children. When
xsl:include is used to include a stylesheet, any
xsl:import elements in the included document are moved up
in the including document to after any existing
xsl:import elements in the including document.
For example,
<xsl:stylesheet xmlns:xsl="http://www.w3.org/XSL/Transform/1.0">
<xsl:import href="article.xsl"/>
<xsl:import href="bigfont.xsl"/>
<xsl:attribute-set name="note-style">
<xsl:attribute name="font-style">italic</xsl:attribute>
</xsl:attribute-set>
</xsl:stylesheet>
The
xsl:stylesheet elements encountered during processing of
a stylesheet that contains xsl:import elements are
treated as forming an import tree. In the import tree,
each xsl:stylesheet element has one import child for each
xsl:import element that it contains. Any
xsl:include elements are resolved before constructing the
import tree. An xsl:stylesheet element in the import tree
is defined to have lower import precedence than another
xsl:stylesheet element in the import tree if it would be
visited before that xsl:stylesheet element in a
post-order traversal of the import tree (i.e. a traversal of the
import tree in which an xsl:stylesheet element is visited
after its import children). Each definition and template
rule has import precedence determined by the
xsl:stylesheet element that contains it.
For example, suppose
stylesheet A imports stylesheets B and C in that order;
stylesheet B imports stylesheet D;
stylesheet C imports stylesheet E.
Then the order of import precedence (lowest first) is D, B, E, C, A.
NOTE: Sincexsl:importelements are required to occur before any definitions or template rules, an implementation that processes imported stylesheets at the point at which it encounters thexsl:importelement will encounter definitions and template rules in increasing order of import precedence.
In general, a definition or template rule with higher import precedence takes precedence over a definition or template rule with lower import precedence. This is defined in detail for each kind of definition and for template rules.
It is an error if a stylesheet directly or indirectly imports
itself. Apart from this, the case where a stylesheet with a particular
URI is imported in multiple places is not treated specially. The
import tree will have a
separate xsl:stylesheet for each place that it is
imported.
NOTE: If xsl:apply-imports is used (see [5.6 Overriding Template Rules]), the behavior may be different from the
behavior if the stylesheet had been imported only at the place with
the highest import
precedence.
Normally an XSLT stylesheet is a complete XML document with the
xsl:stylesheet element as the document element. However,
an XSLT stylesheet may also be embedded in another resource. Two forms
of embedding are possible:
xsl:stylesheet element may occur in an XML
document other than as the document element.To facilitate the second form of embedding, the
xsl:stylesheet element is allowed to have an ID attribute
that specifies a unique identifier.
NOTE: In order for such an attribute to be used with the XPath id function, it must actually be declared in the DTD as being an ID.
The following example shows how the xml-stylesheet
processing instruction [XML Stylesheet] can be used to allow a
document to contain its own stylesheet. The URI reference uses a
relative URI with a fragment identifier to locate the
xsl:stylesheet element:
<?xml-stylesheet type="text/xsl" href="#style1"?>
<!DOCTYPE doc SYSTEM "doc.dtd">
<doc>
<head>
<xsl:stylesheet id="style1"
xmlns:xsl="http://www.w3.org/XSL/Transform/1.0"
xmlns:fo="http://www.w3.org/XSL/Format/1.0">
<xsl:import href="doc.xsl"/>
<xsl:template match="id('foo')">
<fo:block font-weight="bold"><xsl:apply-templates/></fo:block>
</xsl:template>
<xsl:template match="xsl:stylesheet">
<!-- ignore -->
</xsl:template>
</xsl:stylesheet>
</head>
<body>
<para id="foo">
...
</para>
</body>
</doc>
NOTE: The stylesheet that is embedded or may be included or
imported into an stylesheet that is embedded typically needs to
contain a template rule that specifies that
xsl:stylesheet elements are to be ignored.
NOTE: Thetypepseudo-attribute in thexml-stylesheetprocessing instruction identifies the stylesheet language, not the content type of the resource of which the stylesheet is a part.
NOTE: Thetext/xslmedia type has not been registered. No decision has been made on whether a media type other thantext/xmlorapplication/xmlwill be used for XSLT and XSL.
The data model used by XSLT is the same as that used by XPath with the additions described in this section. XSLT operates on source, result and stylesheet documents using the same data model. Any two XML documents that have the same tree will be treated the same by XSLT.
Processing instructions and comments in the stylesheet are ignored: the stylesheet is treated as if neither processing instruction nodes nor comment nodes were included in the tree that represents the stylesheet.
The normal restrictions on the children of the root node are relaxed for the result tree. The result tree may have any sequence of nodes as children that would be possible for an element node. In particular, it may have text node children, and any number of element node children. When written out a result tree may not be a well-formed XML document, but will be a well-formed external general parsed entity.
When the source tree is created by parsing a well-formed XML document, the root node of the source tree will automatically satisfy the normal restrictions of having no text node children and exactly one element child. When the source tree is created in some other way, for example by using the DOM, the usual restrictions are relaxed for the source tree as for the result tree.
An element node also has an associated URI called its base URI, which is used for resolving attribute values that represent relative URIs into absolute URIs. If an element occurs in an external entity, the base URI of that element is the URI of the external entity. Otherwise, the base URI is the base URI of the document.
The root node has a mapping that gives the URI for each unparsed entity declared in the document's DTD. The URI is generated from the system identifier and public identifier specified in the entity declaration. The XSLT processor may use the public identifier to generate a URI for the entity instead of the URI specified in the system identifier. If the XSLT processor does not use the public identifier to generate the URI, it must use the system identifier; if the system identifier is a relative URI, it must be resolved into an absolute URI using the URI of the resource containing the entity declaration as the base URI [RFC2396].
After the tree for a source document or stylesheet document has been constructed, but before it is otherwise processed by XSLT, some text nodes may be stripped. The stripping process takes as input a set of element names for which whitespace must be preserved. The stripping process is applied to both stylesheets and source documents, but the set of whitespace-preserving element names is determined differently for stylesheets and for source documents.
A text node is preserved if any of the following apply:
The element name of the parent of the text node is in the set of whitespace-preserving element names.
The text node contains at least one non-whitespace character. As in XML, a whitespace character is #x20, #x9, #xD or #xA.
An ancestor element of the text node has an
xml:space attribute with a value of
preserve, and no closer ancestor element has
xml:space with a value of
default.
Otherwise, the text node is stripped. When a text node is stripped, it is removed from the tree.
The xml:space attributes are not stripped from the
tree.
NOTE: This implies that if an xml:space attribute is
specified on a literal result element, it will be included in the
result.
For stylesheets, the set of whitespace-preserving element names
consists of just xsl:text.
For source documents, the set of whitespace-preserving element
names is specified by xsl:strip-space and
xsl:preserve-space top-level elements. These elements each
have an elements attribute whose value is a
whitespace-separated list of WildcardNames. Initially, the
set of whitespace-preserving element names contains all element names.
If an element name matches a WildcardName in an
xsl:strip-space element, then it is removed from the set
of whitespace-preserving element names. If an element name matches a
WildcardName in an
xsl:preserve-space element, then it is added to the set
of whitespace-preserving element names. Conflicts between matches to
xsl:strip-space and xsl:preserve-space
elements are resolved the same way as conflicts between template rules
(see [5.5 Conflict Resolution for Template Rules]). Thus, the applicable match for a
particular element name is determined as follows:
First, any match with lower import precedence than another match is ignored.
Next, any match with a WildcardName that has a lower default priority than the default priority of the WildcardName of another match is ignored.
It is an error if this leaves more than one match. An XSLT processor may signal the error; if it does not signal the error, it must recover by choosing, from amongst the matches that are left, the one that occurs last in the stylesheet.
XSLT uses the expression language defined by XPath [XPath]. Expressions are used in XSLT for a variety of purposes including:
An expression must match the XPath production Expr.
Expressions occur as the value of certain attributes on XSLT-defined elements and within curly braces in attribute value templates.
In XSLT, an outermost expression (i.e. an expression that is not part of another expression) gets its context as follows:
the context node comes from the current node
the context position comes from the position of the current node in the current node list; the first position is 1
the context size comes from the size of the current node list
the variable bindings are the bindings in scope on the element which has the attribute in which the expression occurs (see [11 Variables and Parameters])
the set of namespace declarations are those in scope on the
element which has the attribute in which the expression occurs; the default
namespace (as declared by xmlns) is not part of this
set
the function library consists of the core function library together with the additional functions defined in [13 Additional Functions] and extension functions as described in [14 Extensions]; it is an error for an expression to include a call to any other function
A list of source nodes is processed to create a result tree fragment. The result tree is constructed by processing a list containing just the root node. A list of source nodes is processed by appending the result tree structure created by processing each of the members of the list in order. A node is processed by finding all the template rules with patterns that match the node, and choosing the best amongst them. The chosen rule's template is then instantiated for the node. During the instantiation of a template, the node for which the template is being instantiated is called the current node; the list of source nodes that is being processed is called the current node list. The current node is always a member of the current node list. A template typically contains instructions that select an additional list of source nodes for processing. The process of matching, instantiation and selection is continued recursively until no new source nodes are selected for processing.
Implementations are free to process the source document in any way that produces the same result as if it were processed using this processing model.
Template rules identify the nodes to which they apply by using a pattern. In addition, patterns are used for numbering (see [7.7 Numbering]) and for declaring keys (see [13.2 Keys]). A pattern specifies a set of conditions on a node. A node that satisfies the conditions matches the pattern; a node that does not satisfy the conditions does not match the pattern. The syntax for patterns is a subset of the syntax for expressions. In particular, location paths that meet certain restrictions can be used as patterns. An expression that is also a pattern always evaluates to an object of type node-set. A node matches a pattern if the node is a member of the result of evaluating the pattern as an expression with respect to some possible context; the possible contexts are those whose context node is the node being matched or one of its ancestors.
Here are some examples of patterns:
para matches any para element
* matches any element
chapter|appendix matches any
chapter element and any appendix
element
olist/item matches any item element with
an olist parent
appendix//para matches any para element with
an appendix ancestor element
/ matches the root node
text() matches any text node
processing-instruction() matches any processing
instruction
node() matches any node other than an attribute
node and the root node
id("W11") matches the element with unique ID
W11
para[1] matches any para element
that is the first para child element of its
parent
*[position()=1 and self::para] matches any
para element that is the first child element of its
parent
para[last()=1] matches any para
element that is the only child element of its parent
items/item[position()>1] matches any
item element that has a items parent and
that is not the first item child of its parent
item[position() mod 2 = 1] would be true for any
item element that is an odd-numbered item
child of its parent.
div[@class="appendix"]//p matches any
p element with a div ancestor element that
has a class attribute with value
appendix
@class matches any class attribute
(not any element that has a class
attribute)
@* matches any attribute
A pattern must match the grammar for Pattern. A Pattern is
a set of location path patterns separated by |. A location
path pattern is a location path none of the steps of which uses either
AxisNames or . or
... Location path patterns can also start with an
id or key function call with
a literal argument. Predicates in a pattern can use arbitrary
expressions just like predicates in a location path.
| [1] | Pattern | ::= | LocationPathPattern | |
| | Pattern '|' LocationPathPattern | ||||
| [2] | LocationPathPattern | ::= | '/' RelativePathPattern? | |
| | IdKeyPattern (('/' | '//') RelativePathPattern)? | ||||
| | '//'? RelativePathPattern | ||||
| [3] | IdKeyPattern | ::= | 'id' '(' Literal ')' | |
| | 'key' '(' Literal ',' Literal ')' | ||||
| [4] | RelativePathPattern | ::= | StepPattern | |
| | RelativePathPattern '/' StepPattern | ||||
| | RelativePathPattern '//' StepPattern | ||||
| [5] | StepPattern | ::= | AbbreviatedAxisSpecifier NodeTest Predicate* |
A pattern is defined to match a node if and only if there is possible context such that when the pattern is evaluated as an expression with that context, the node is a member of the resulting node-set. When a node is being matched, the possible contexts have a context node that is the node being matched or any ancestor of that node, and a context node list containing just the context node.
For example, p matches any p element,
because for any p if the expression p is
evaluated with the parent of the p element as context the
resulting node-set will contain that p element as one of
its members.
NOTE: This matches even a p element that is the
document element, since the document root is the parent of the
document element.
Although the semantics of patterns are specified indirectly in
terms of expression evaluation, it is easy to understand the meaning
of a pattern directly without thinking in terms of expression
evaluation. In a pattern, | indicates alternatives; a
pattern with one or more | separated alternatives matches
if any one of the alternative matches. A pattern that consists of a
sequence of StepPatterns separated by
/ or // is matched from right to left. The
pattern only matches if the rightmost StepPattern matches and a suitable element
matches the rest of the pattern; if the separator is /
then only the parent is a suitable element; if the separator is
//, then any ancestor is a suitable element. A StepPattern that's a NodeTest matches if the NodeTest is true for the node and the
node is not an attribute node. A StepPattern that starts with @
matches if the node is an attribute node and the WildcardName matches the name of
the attribute. When [] is present, then the first PredicateExpr in a StepPattern is evaluated with the node being
matched as the context node and the siblings of the context node that
match the NodeTest as the
context node list, unless the node being matched is an attribute node,
in which case the context node list is all the attributes that have
the same parent as the attribute being matched and that match the WildcardName.
For example
appendix//ulist/item[position()=1]
matches a node if and only if all of the following are true:
the NodeTest item is
true for the node and the node is not an attribute; in other words the
node is an item element
evaluating the PredicateExpr
position()=1 with the node as context node and the
siblings of the node that are item elements as the
context node list yields true
the node has a parent that matches
appendix//ulist; this will be true if the parent is a
ulist element that has an appendix ancestor
element.
A template rule is specified with the xsl:template
element. The match attribute is a Pattern that identifies the source node or nodes
to which the rule applies. The match attribute is
required unless the xsl:template element has a
name attribute (see [6 Named Templates]).
The content of the xsl:template element is the
template.
For example, an XML document might contain:
This is an <emph>important</emph> point.
The following template rule matches emph elements and
has a template, which produces a fo:inline-sequence
formatting object with a font-weight property of
bold.
<xsl:template match="emph">
<fo:inline-sequence font-weight="bold">
<xsl:apply-templates/>
</fo:inline-sequence>
</xsl:template>
NOTE: Examples in this document use thefo:prefix for the namespacehttp://www.w3.org/XSL/Format/1.0, which is the namespace of the formatting objects defined in [XSL].
As described later, the xsl:apply-templates element
recursively processes the children of the source element.
This example creates a block for a chapter element and
then processes its immediate children.
<xsl:template match="chapter">
<fo:block>
<xsl:apply-templates/>
</fo:block>
</xsl:template>
In the absence of a select attribute, the
xsl:apply-templates instruction processes all of the
children of the current node, including text nodes. However, text
nodes that have been stripped as specified in [3.4 Whitespace Stripping]
will not be processed. If stripping of whitespace nodes has not been
enabled for an element, then all whitespace in the content of the
element will be processed as text, and, in particular, whitespace
between child elements will count in determining the position of a
child element as returned by the position
function.
A select attribute can be used to process nodes
selected by an expression instead of all children. The value of the
select attribute is an expression. The expression must
evaluate to a node-set. The selected set of nodes is processed in
document order, unless a sorting specification is present (see
[10 Sorting]). The following example processes all of the
author children of the author-group:
<xsl:template match="author-group">
<fo:inline-sequence>
<xsl:apply-templates select="author"/>
</fo:inline-sequence>
</xsl:template>
The following example processes all of the first-names
of the authors that are children of
author-group:
<xsl:template match="author-group">
<fo:inline-sequence>
<xsl:apply-templates select="author/first-name"/>
</fo:inline-sequence>
</xsl:template>
This example processes all of the heading elements
contained in the book element.
<xsl:template match="book">
<fo:block>
<xsl:apply-templates select=".//heading"/>
</fo:block>
</xsl:template>
It is also possible to process elements that are not descendants of
the current node. This example assumes that a department
element contains group and employee elements
(at some level). It finds an employee's department and then processes
the group children of the department.
<xsl:template match="employee">
<fo:block>
Employee <xsl:apply-templates select="name"/> belongs to group
<xsl:apply-templates select="ancestor::department/group"/>
</fo:block>
</xsl:template>
Multiple xsl:apply-templates elements can be used within a
single template to do simple reordering. The following example
creates two HTML tables. The first table is filled with domestic sales
while the second table is filled with foreign sales.
<xsl:template match="product">
<TABLE>
<xsl:apply-templates select="sales/domestic"/>
</TABLE>
<TABLE>
<xsl:apply-templates select="sales/foreign"/>
</TABLE>
</xsl:template>
NOTE: It is possible for there to be two matching descendants where one is a descendant of the other. This case is not treated specially: both descendants will be processed as usual. For example, given a source document<doc><div><div></div></div></doc>the rule<xsl:template match="doc"> <xsl:apply-templates select=".//div"/> </xsl:template>will process both the outerdivand innerdivelements.
NOTE: Typically,xsl:apply-templatesis used to process only nodes that are descendants of the current node. Such use ofxsl:apply-templatescannot result in non-terminating processing loops. However, whenxsl:apply-templatesis used to process elements that are not descendants of the current node, the possibility arises of non-terminating loops. For example,<xsl:template match="foo"> <xsl:apply-templates select="."/> </xsl:template>Implementations may be able to detect such loops in some cases, but the possibility exists that a stylesheet may enter a non-terminating loop that an implementation is unable to detect. This may present a denial of service security risk.
It is possible for a source node to match more than one template rule. The template rule to be used is determined as follows:
First, all matching template rules that have lower import precedence than the matching template rule or rules with the highest import precedence are eliminated from consideration.
Next, all matching template rules that have lower priority
than the matching template rule or rules with the highest priority are
eliminated from consideration. The priority of a template rule is
specified by the priority attribute on the template rule.
The value of this must be a real number (positive or negative),
matching the production Number
with an optional leading minus sign (-). The default
priority is computed as follows:
If the pattern contains multiple alternatives separated by
|, then it is treated equivalently to a set of template
rules one for each alternative.
If the pattern has the form of a QName optionally preceded by an
@ character or has the form
processing-instruction(Literal), then the priority is 0.
If the pattern has the form NCName:*, then the
priority is -0.25.
Otherwise, if the pattern consists of just a NodeTest, then the priority is -0.5.
Otherwise, the priority is 0.5.
Thus, the most common kind of pattern (a pattern that tests for a node with a particular type and a particular expanded name) has priority 0. The next less specific kind of pattern (a pattern that tests for a node with a particular type and an expanded name with a particular namespace URI) has priority -0.25. Patterns less specific than this (patterns that just tests for nodes with particular types) have priority -0.5. Patterns more specific than the most common kind of pattern have priority 0.5.
It is an error if this leaves more than one matching template rule. An XSLT processor may signal the error; if it does not signal the error, it must recover by choosing, from amongst the matching template rules that are left, the one that occurs last in the stylesheet.
A template rule that is being used to override a template rule in
an imported stylesheet (see [5.5 Conflict Resolution for Template Rules]) can use the
xsl:apply-imports element to invoke the overridden
template rule.
At any point in the processing of a stylesheet, there is a
current template rule. Whenever a template rule is
chosen by matching a pattern, the template rule becomes the current
template rule for the instantiation of the rule's template. When an
xsl:for-each element is instantiated, the current
template rule becomes null for the instantiation of the content of the
xsl:for-each element.
xsl:apply-imports processes the current node using
only template rules that were imported into the stylesheet element
containing the current template rule; the node is processed in the
current template rule's mode. It is an error if
xsl:apply-imports is instantiated when the current
template rule is null.
For example, suppose the stylesheet doc.xsl contains a
template rule for example elements:
<xsl:template match="example"> <pre><xsl:apply-templates/></pre> </xsl:template>
Another stylesheet could import doc.xsl and modify the
treatment of example elements as follows:
<xsl:import href="doc.xsl"/>
<xsl:template match="example">
<div style="border: solid red">
<xsl:apply-imports/>
</div>
</xsl:template>
The combined effect would be to transform an example
into an element of the form:
<div style="border: solid red"><pre>...</pre></div>
Modes allow an element to be processed multiple times, each time producing a different result.
Both xsl:template and xsl:apply-templates
have an optional mode attribute. The value of the
mode attribute is a QName, which is expanded as described
in [2.4 Qualified Names]. If xsl:template does not have
a match attribute it must not have a mode
attribute. If an xsl:apply-templates element has a
mode attribute, then it applies only to those template
rules from xsl:template elements that have a
mode attribute with the same value; if an
xsl:apply-templates element does not have a
mode attribute, then it applies only to those template
rules from xsl:template elements that do not have a
mode attribute.
There is a built-in template rule to allow recursive processing to continue in the absence of a successful pattern match by an explicit template rule in the stylesheet. This template rule applies to both element nodes and the root node. The following shows the equivalent of the built-in template rule:
<xsl:template match="*|/"> <xsl:apply-templates/> </xsl:template>
There is also a built-in template rule for each mode, which allows
recursive processing to continue in the same mode in the absence of a
successful pattern match by an explicit template rule in the
stylesheet. This template rule applies to both element nodes and the
root node. The following shows the equivalent of the built-in
template rule for mode m.
<xsl:template match="*|/" mode="m"> <xsl:apply-templates mode="m"/> </xsl:template>
There is also a built-in template rule for text and attribute nodes that copies text through:
<xsl:template match="text()|@*"> <xsl:value-of select="."/> </xsl:template>
The built-in template rule for processing instructions and comments is to do nothing.
<xsl:template match="processing-instruction()|comment()"/>
The built-in template rule for namespace nodes is also to do nothing. There is no pattern that can match a namespace node; so the built-in template rule is the only template rule that is applied for namespace nodes.
The built-in template rules are treated as if they were imported implicitly before the stylesheet and so have lower import precedence than all other template rules. Thus, the author can override a built-in template rule by including an explicit template rule.
Templates can be invoked by name. An xsl:template
element with a name attribute specifies a named template.
The value of the name attribute is a QName, which is expanded as described
in [2.4 Qualified Names]. If an xsl:template element has
a name attribute, it may, but need not, also have a
match attribute. An xsl:call-template
element invokes a template by name; it has a required
name attribute that identifies the template to be
invoked. Unlike xsl:apply-templates,
xsl:call-template does not change the current node or the
current node list.
The match and mode attributes on an
xsl:template element do not affect whether the template
is invoked by an xsl:call-template element. Similarly,
the name attribute on an xsl:template
element does not affect whether the template is invoked by a
xsl:apply-templates element.
It is an error if a stylesheet contains more than one template with the same name and same import precedence.
This section describes instructions that directly create nodes in the result tree.
In a template, an element in the stylesheet that does not belong to
the XSLT namespace and that is not an extension element (see [14.1 Extension Elements]) is instantiated to create an element node
of the same type. The content of the element is a template, which is
instantiated to give the content of the created element node. The
created element node will have the attribute nodes that were present
on the element node in the stylesheet tree, other than attributes with
names in the XSLT namespace. The created element node will also have
the namespace nodes that were present on the element node in the
stylesheet tree with the exception of any namespace node whose
string-value is the XSLT namespace URI
(http://www.w3.org/XSL/Transform/1.0), a namespace URI
treated the same as the XSLT namespace URI (see [2.5 Forwards-Compatible Processing]), or a namespace URI declared as an extension
namespace (see [14.1 Extension Elements]).
The value of an attribute of a literal result element is
interpreted as an attribute
value template: it can contain expressions contained
in curly braces ({}).
Namespace URIs that occur literally in the stylesheet and that are being used to create nodes in the result tree can be quoted. This applies to:
the namespace URI in the expanded name of a literal result element in the stylesheet
the namespace URI in the expanded name of an attribute specified on a literal result element in the stylesheet
the string-value of a namespace node on a literal result element in the stylesheet
A namespace URI is quoted by prefixing it with the string
quote:. This prefix will be removed when the template is
instantiated to create the result element node with its associated
attribute nodes and namespace nodes.
When literal result elements are being used to create element, attribute, or namespace nodes that use the XSLT namespace URI, the namespace must be quoted to avoid misinterpretation by the XSLT processor.
NOTE: It may be necessary also to quote other namespaces. For example, literal result elements belonging to a namespace dealing with digital signatures might cause XSLT stylesheets to be mishandled by general-purpose security software; quoting the namespace would avoid the possibility of such mishandling.
For example, the stylesheet
<xsl:stylesheet
xmlns:xsl="http://www.w3.org/XSL/Transform/1.0"
xmlns:fo="http://www.w3.org/XSL/Format/1.0"
xmlns:qxsl="quote:http://www.w3.org/XSL/Transform/1.0">
<xsl:template match="/">
<qxsl:stylesheet>
<xsl:apply-templates/>
</qxsl:stylesheet>
</xsl:template>
<xsl:template match="block">
<qxsl:template match="{.}">
<fo:block><qxsl:apply-templates/></fo:block>
</qxsl:template>
</xsl:template>
</xsl:stylesheet>
will generate an XSLT stylesheet from a document of the form:
<elements> <block>p</block> <block>h1</block> <block>h2</block> <block>h3</block> <block>h4</block> </elements>
xsl:element
The xsl:element element allows an element to be
created with a computed name. The expanded-name of the element to be
created is specified by a required name attribute and an
optional namespace attribute. The content of the
xsl:element element is a template for the attributes and
children of the created element.
The name attribute is interpreted as an attribute value template.
It is an error if the string that results from instantiating the
attribute value template is not a QName. An XSLT processor may signal
the error; if it does not signal the error, it must recover by not
outputting the element or its attributes, and outputting only the
children of the element. If the namespace attribute is
not present then the QName is
expanded into an expanded-name using the namespace declarations in
effect for the xsl:element element, including any default
namespace declaration.
If the namespace attribute is present, then it also is
interpreted as an attribute
value template. The string that results from instantiating
the attribute value template should be a URI reference. It is not an
error if the string is not a syntactically legal URI reference. If
the string is empty, then the expanded-name of the element has a null
namespace URI. Otherwise, the string is used as the namespace URI of
the expanded-name of the element to be created. The local part of the
QName specified by the
name attribute is used as the local part of the
expanded-name of the element to be created.
XSLT processors may make use of the prefix of the QName specified in the
name attribute when selecting the prefix used for
outputting the created element as XML. They are not however required
to do so.
xsl:attribute
The xsl:attribute element can be used to add
attributes to result elements whether created by literal result
elements in the stylesheet or by instructions such as
xsl:element. The expanded-name of the attribute to be
created is specified by a required name attribute and an
optional namespace attribute. Instantiating an
xsl:attribute element adds an attribute node to the
containing result element node. The content of the
xsl:attribute element is a template for the value of the
created attribute.
The name attribute is interpreted as an attribute value template.
It is an error if the string that results from instantiating the
attribute value template is not a QName. An XSLT processor may signal
the error; if it does not signal the error, it must recover by not
outputting the attribute. If the namespace attribute is
not present, then the QName is
expanded into an expanded-name using the namespace declarations in
effect for the xsl:attribute element, not
including any default namespace declaration.
If the namespace attribute is present, then it also is
interpreted as an attribute
value template. The string that results from instantiating
it should be a URI reference. It is not an error if the string is not
a syntactically legal URI reference. If the string is empty, then the
expanded-name of the attribute has a null namespace URI. Otherwise,
the string is used as the namespace URI of the expanded-name of the
attribute to be created. The local part of the QName specified by the
name attribute is used as the local part of the
expanded-name of the attribute to be created.
XSLT processors may make use of the prefix of the QName specified in the
name attribute when selecting the prefix used for
outputting the created attribute as XML. They are not however
required to do so.
Adding an attribute to an element replaces any existing attribute of that element with the same expanded-name.
The following are all errors:
Adding an attribute to an element after children have been added to it; implementations may either signal the error or ignore the attribute.
Adding an attribute to a node that is not an element; implementations may either signal the error or ignore the attribute.
Creating anything other than characters during the
instantiation of the content of the xsl:attribute
element; implementations may either signal the error or ignore the
offending nodes.
NOTE: When anxsl:attributecontains a text node with a newline, then the XML output must contain a character reference. For example,<xsl:attribute name="a">x y</xsl:attribute>will result in the outputa="x
y"(or with any equivalent character reference). The XML output cannot bea="x y"This is because XML 1.0 requires newline characters in attribute values to be normalized into spaces but requires character references to newline characters not to be normalized. The attribute values in the data model represent the attribute value after normalization. If a newline occurring in an attribute value in the tree was output as a newline character rather than as character reference, then the attribute value in the tree created by reparsing the XML would contain a space not a newline, which would mean that the tree had not been output correctly.
The xsl:attribute-set element defines a named set of
attributes. The name attribute specifies the name of the
attribute set. The value of the name attribute is a QName, which is expanded as described
in [2.4 Qualified Names]. The content of the xsl:attribute-set
element consists of zero or more xsl:attribute elements
that specify the attributes in the set.
Attribute sets are used by specifying a
use-attribute-sets attribute on xsl:element,
xsl:copy (see [7.5 Copying]) or
xsl:attribute-set elements. The value of the
use-attribute-sets attribute is a whitespace-separated
list of names of attribute sets. Each name is specified as a QName, which is expanded as described
in [2.4 Qualified Names]. Specifying a
use-attribute-sets attribute is equivalent to adding
xsl:attribute elements for each of the attributes in each
of the named attribute sets to the beginning of the content of the
element with the use-attribute-sets attribute, in the
same order in which the names of the attribute sets are specified in
the use-attribute-sets attribute. It is an error if use
of use-attribute-sets attributes on
xsl:attribute-set elements causes an attribute set to
directly or indirectly use itself.
Attribute sets can also be used by specifying an
xsl:use-attribute-sets attribute on a literal result
element. The value of the xsl:use-attribute-sets
attribute is a whitespace-separated list of names of attribute sets.
The xsl:use-attribute-sets attribute has the same effect
as the use-attribute-sets attribute on
xsl:element with the additional rule that attributes
specified on the literal result element itself are treated as if they
were specified by xsl:attribute elements before any
actual xsl:attribute elements but after any
xsl:attribute elements implied by the
xsl:use-attribute-sets attribute. Thus, for a literal
result element, attributes from attribute sets named in an
xsl:use-attribute-sets attribute will be added first, in
the order listed in the attribute; next, attributes specified on the
literal result element will be added; finally, any attributes
specified by xsl:attribute elements will be added. Since
adding an attribute to an element replaces any existing attribute of
that element with the same name, this means that attributes specified
in attribute sets can be overridden by attributes specified on the
literal result element itself.
The template within each xsl:attribute element in an
xsl:attribute-set element is instantiated each time the
attribute set is used; it is instantiated using the same current node
and current node list as is used for instantiating the element bearing
the use-attribute-sets or
xsl:use-attribute-sets attribute. However, it is the
position in the stylesheet of the xsl:attribute element
rather than of the element bearing the use-attribute-sets
or xsl:use-attribute-sets attribute that determines which
variable bindings are visible (see [11 Variables and Parameters]); thus,
only variables and parameters declared by top-level xsl:variable and
xsl:param elements are visible.
The following example creates a named attribute set
title-style and uses it in a template rule.
<xsl:template match="chapter/heading">
<fo:block quadding="start" xsl:use-attribute-sets="title-style">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:attribute-set name="title-style">
<xsl:attribute name="font-size">12pt</xsl:attribute>
<xsl:attribute name="font-weight">bold</xsl:attribute>
</xsl:attribute-set>
Multiple definitions of an attribute set with the same expanded-name are merged. An attribute from a definition that has higher import precedence takes precedence over an attribute from a definition that has lower import precedence. It is an error if there are two attribute sets with the same expanded-name and with equal import precedence and that both contain the same attribute unless there is a definition of the attribute set with higher import precedence that also contains the attribute. An XSLT processor may signal the error; if it does not signal the error, it must recover by choosing from amongst the definitions that specify the attribute that have the highest import precedence the one that was specified last in the stylesheet. Where the attributes in an attribute set were specified is relevant only in merging the attributes into the attribute set; it makes no difference when the attribute set is used.
A template can also contain text nodes. Each text node in a template remaining after whitespace has been stripped as specified in [3.4 Whitespace Stripping] will create a text node with the same string-value in the result tree. Adjacent text nodes in the result tree are automatically merged.
Note that text is processed at the tree level. Thus, markup of
< in a template will be represented in the
stylesheet tree by a text node that includes the character
<. This will create a text node in the result tree
that contains a < character, which will be represented
by the markup < (or an equivalent character
reference) when the result tree is externalized as an XML
document.
Literal data characters may also be wrapped in an
xsl:text element. This wrapping may change what
whitespace characters are stripped (see [3.4 Whitespace Stripping]) but
does not affect how the characters are handled by the XSLT processor
thereafter.
The xsl:processing-instruction element is instantiated
to create a processing instruction node. The content of the
xsl:processing-instruction element is a template for the
string-value of the processing instruction node. The
xsl:processing-instruction element has a required
name attribute that specifies the name of the processing
instruction node. The value of the name attribute is
interpreted as an attribute
value template.
For example, this
<xsl:processing-instruction name="xml-stylesheet">href="book.css" type="text/css"</xsl:processing-instruction>
would create the processing instruction
<?xml-stylesheet href="book.css" type="text/css"?>
It is an error if the string that results from instantiating the
name attribute is not both an NCName and a PITarget. An XSLT processor may signal
the error; if it does not signal the error, it must recover by not
outputting the processing instruction.
NOTE: This means that xsl:processing-instruction
cannot be used to output an XML declaration.
It is an error if instantiating the content of
xsl:processing-instruction creates anything other than
characters. An XSLT processor may signal the error; if it does not
signal the error, it must recover by ignoring the offending nodes
together with their content.
It is an error if the result of instantiating the content of the
xsl:processing-instruction contains the string
?>. An XSLT processor may signal the error; if it does
not signal the error, it must recover by inserting a space after any
occurrence of ? that is followed by a >.
The xsl:comment element is instantiated to create a
comment node in the result tree. The content of the
xsl:comment element is a template for the string-value of
the comment node.
For example, this
<xsl:comment>This file is automatically generated. Do not edit!</xsl:comment>
would create the comment
<!--This file is automatically generated. Do not edit!-->
It is an error if instantiating the content of
xsl:comment creates anything other than characters. An
XSLT processor may signal the error; if it does not signal the error,
it must recover by ignoring the offending nodes together with their
content.
It is an error if the result of instantiating the content of the
xsl:comment contains the string -- or ends
with -. An XSLT processor may signal the error; if it
does not signal the error, it must recover by inserting a space after
any occurrence of - that is followed by another
- or that ends the comment.
The xsl:copy element provides an easy way of copying
the current node. The xsl:copy element is replaced by a
copy of the current node. The namespace nodes of the current node are
automatically copied as well, but the attributes and children of the
node are not automatically copied. The content of the
xsl:copy element is a template for the attributes and
children of the created node; the content is not used for nodes of
types that do not have attributes or children (attributes, text,
comments and processing instructions).
The xsl:copy element may have a
use-attribute-sets attribute (see [7.1.4 Named Attribute Sets]). This is used only when copying element
nodes.
The root node is treated specially because the root node of the
result tree is created implicitly. When the current node is the root
node, xsl:copy will not create a root node, but will just
use the content template.
For example, the identity transformation can be written using
xsl:copy as follows:
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
When the current node is an attribute, then if it would be an error
to use xsl:attribute to create an attribute with the same
name as the current node, then it is also an error to use
xsl:copy (see [7.1.3 Creating Attributes with xsl:attribute]).
Within a template, the xsl:value-of element can be
used to compute generated text, for example by extracting text from
the source tree or by inserting the value of a variable. The
xsl:value-of element does this with an expression that is specified as the
value of the select attribute. Expressions can
also be used inside attribute values of literal result elements by
enclosing the expression in curly braces ({}).
xsl:value-of
The xsl:value-of element is instantiated to create a
text node in the result tree. The required select
attribute is an expression;
this expression is evaluated and the resulting object is converted to
a string as if by a call to the string
function. The string specifies the string-value of the created text
node. If the string is empty, no text node will be created. The
created text node will be merged with any adjacent text nodes.
The xsl:copy-of element can be used to copy a node-set
over to the result tree without converting it to a string. See [11.3 Using Values of Variables and Parameters with
xsl:copy-of].
For example, the following creates an HTML paragraph from a
person element with first-name and
surname attributes. The paragraph will contain the value
of the first-name attribute of the current node followed
by a space and the value of the surname attribute of the
current node.
<xsl:template match="person"> <p> <xsl:value-of select="@first-name"/> <xsl:text> </xsl:text> <xsl:value-of select="@surname"/> </p> </xsl:template>
For example, the following creates an HTML paragraph from a
person element with first-name and
surname children elements. The paragraph will contain
the string-value of the first first-name child element of
the current node followed by a space and the string-value of the first
surname child element of the current node.
<xsl:template match="person"> <p> <xsl:value-of select="first-name"/> <xsl:text> </xsl:text> <xsl:value-of select="surname"/> </p> </xsl:template>
The following precedes each procedure element with a
paragraph containing the security level of the procedure. It assumes
that the security level that applies to a procedure is determined by a
security attribute on the procedure element or on an
ancestor element of the procedure. It also assumes that if more than
one such element has a security attribute then the
security level is determined by the element that is closest to the
procedure.
<xsl:template match="procedure">
<fo:block>
<xsl:value-of select="ancestor-or-self::*[@security][1]/@security"/>
</fo:block>
<xsl:apply-templates/>
</xsl:template>
In an attribute value that is interpreted as an
attribute value template, such as an attribute of a
literal result element, an expression can be used by surrounding
the expression with curly braces ({}). The
attribute value template is instantiated by replacing the expression
together with surrounding curly braces by the result of evaluating the
expression and converting the resulting object to a string as if by a
call to the string function. Curly braces are
not recognized in an attribute value in an XSLT stylesheet unless the
attribute is specifically stated to be one that is interpreted as an
attribute value template.
NOTE: Not all attributes are interpreted as attribute value
templates. Attributes whose value is an expression or pattern,
attributes of top-level elements
and attributes that refer to named XSLT objects are not interpreted as
attribute value templates. In addition, xmlns attributes
are not interpreted as attribute value templates: it would not be
conformant with the XML Namespaces Recommendation to do
this.
The following example creates an img result element
from a photograph element in the source; the value of the
src attribute of the img element is computed
from the value of the image-dir variable and the
string-value of the href child of the
photograph element; the value of the width
attribute of the img element is computed from the value
of the width attribute of the size child of
the photograph element:
<xsl:variable name="image-dir">/images</xsl:variable>
<xsl:template match="photograph">
<img src="{$image-dir}/{href}" width="{size/@width}"/>
</xsl:template>
With this source
<photograph> <href>headquarters.jpg</href> <size width="300"/> </photograph>
the result would be
<img src="/images/headquarters.jpg" width="300"/>
When an attribute value template is instantiated, a double left or right curly brace outside an expression will be replaced by a single curly brace. It is an error if a right curly brace occurs in an attribute value template outside an expression without being followed by a second right curly brace. A right curly brace inside a Literal in an expression is not recognized as terminating the expression.
Curly braces are not recognized recursively inside expressions. For example:
<a href="#{id({@ref})/title}">
is not allowed. Instead, use simply:
<a href="#{id(@ref)/title}">
The xsl:number element is used to insert a formatted
number into the result tree. The number to be inserted may be
specified by an expression. The value attribute contains
an expression. The expression
is evaluated and the resulting object is converted to a number as if
by a call to the number function. The number is
rounded to an integer and then converted to a string using the
attributes specified in [7.7.1 Number to String Conversion Attributes]; when used with
xsl:number the value of each of these attributes is
interpreted as an attribute
value template. After conversion, the resulting string is
inserted in the result tree. For example, the following example
numbers a sorted list:
<xsl:template match="items">
<xsl:for-each select="item">
<xsl:sort select="."/>
<p>
<xsl:number value="position()" format="1. "/>
<xsl:value-of select="."/>
</p>
</xsl:for-each>
</xsl:template>
If no value attribute is specified, then the
xsl:number element inserts a number based on the position
of the current node in the source tree. The following attributes
control how the current node is to be numbered:
The level attribute specifies what levels of the
source tree should be considered; it has the values
single, multiple or any. The
default is single.
The count attribute is a pattern that specifies
what nodes should be counted at those levels. If count
attribute is not specified, then it defaults to the pattern that
matches any node with the same node type as the current node and, if
the current node has a name, with the same name as the current
node.
The from attribute is a pattern that specifies
where counting starts from.
In addition the xsl:number element has the attributes
specified in [7.7.1 Number to String Conversion Attributes] for number to string
conversion.
The xsl:number element first constructs a list of
positive integers using the level, count and
from attributes:
When level="single", it goes up to the nearest
ancestor (including the current node as its own ancestor) that matches
the count pattern, and constructs a list of length one
containing one plus the number of preceding siblings of that ancestor
that match the count pattern. If there is no such
ancestor, it constructs an empty list. If the from
attribute is specified, then the only ancestors that are searched are
those that are descendants of the nearest ancestor that matches the
from pattern. Preceding siblings has the same meaning
here as with the preceding-sibling axis; thus neither
attribute nor namespaces nodes have any preceding siblings.
When level="multiple", it constructs a list of all
ancestors of the current node in document order followed by the
element itself; it then selects from the list those nodes that match
the count pattern; it then maps each node in the list to
one plus the number of preceding siblings of that node that match the
count pattern. If the from attribute is
specified, then the only ancestors that are searched are those that
are descendants of the nearest ancestor that matches the
from pattern. Preceding siblings has the same meaning
here as with the preceding-sibling axis; thus neither
attribute nor namespaces nodes have any preceding siblings.
When level="any", it constructs a list of length
one containing the number of nodes that match the count
pattern and belong to the set containing the current node and all
nodes at any level of the document that are before the current node in
document order, excluding any namespace and attribute nodes (in other
words the union of the members of the preceding and
ancestor-or-self axes). If the from
attribute is specified, then only nodes after the first node before
the current node that match the from pattern are
considered.
The list of numbers is then converted into a string using the
attributes specified in [7.7.1 Number to String Conversion Attributes]; when used with
xsl:number the value of each of these attributes is
interpreted as an attribute
value template. After conversion, the resulting string is
inserted in the result tree.
The following would number the items in an ordered list:
<xsl:template match="ol/item">
<fo:block>
<xsl:number/><xsl:text>. </xsl:text><xsl:apply-templates/>
</fo:block>
<xsl:template>
The following two rules would number title elements.
This is intended for a document that contains a sequence of chapters
followed by a sequence of appendices, where both chapters and
appendices contain sections, which in turn contain subsections.
Chapters are numbered 1, 2, 3; appendices are numbered A, B, C;
sections in chapters are numbered 1.1, 1.2, 1.3; sections in
appendices are numbered A.1, A.2, A.3.
<xsl:template match="title">
<fo:block>
<xsl:number level="multiple"
count="chapter|section|subsection"
format="1.1. "/>
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:template match="appendix//title" priority="1">
<fo:block>
<xsl:number level="multiple"
count="appendix|section|subsection"
format="A.1. "/>
<xsl:apply-templates/>
</fo:block>
</xsl:template>
The following example numbers notes sequentially within a chapter:
<xsl:template match="note">
<fo:block>
<xsl:number level="any" from="chapter" format="(1) "/>
<xsl:apply-templates/>
</fo:block>
</xsl:template>
The following example would number H4 elements in HTML
with a three-part label:
<xsl:template match="H4"> <fo:block> <xsl:number level="any" from="H1" count="H2"/> <xsl:text>.</xsl:text> <xsl:number level="any" from="H2" count="H3"/> <xsl:text>.</xsl:text> <xsl:number level="any" from="H3" count="H4"/> <xsl:text> </xsl:text> <xsl:apply-templates/> </fo:block> </xsl:template>
The following attributes are used to control conversion of a list of numbers into a string. The numbers are integers greater than 0. The attributes are all optional.
The main attribute is format. The default value for
the format attribute is 1. The
format attribute is split into a sequence of tokens where
each token is a maximal sequence of alphanumeric characters or a
maximal sequence of non-alphanumeric characters. Alphanumeric means
any character that has a Unicode category of Nd, Nl, No, Lu, Ll, Lt,
Lm or Lo. The alphanumeric tokens (format tokens) specify the format
to be used for each number in the list. If the first token is a
non-alphanumeric token, then the constructed string will start with
that token; if the last token is non-alphanumeric token, then the
constructed string will end with that token. Non-alphanumeric tokens
that occur between two format tokens are separator tokens that are
used to join numbers in the list. The n-th format token will be used
to format the n-th number in the list. If there are more numbers than
format tokens, then the last format token will be used to format
remaining numbers. If there are no format tokens, then a format token
of 1 is used to format all numbers. The format token
specifies the string to be used to represent the number 1. Each
number after the first will be separated from the preceding number by
the separator token preceding the format token used to format that
number, or, if there are no separator tokens, then by
..
Format tokens are a superset of the allowed values for the
type attribute for the OL element in HTML
4.0 and are interpreted as follows:
Any token where the last character has a decimal digit value
of 1 (as specified in the Unicode 2.0 character property database),
and the Unicode value of preceding characters is one less than the
Unicode value of the last character. This generates a decimal
representation of the number where each number is at least as long as
the format token. Thus, a format token 1 generates the
sequence 1 2 ... 10 11 12 ..., and a format token
01 generates the sequence 01 02 ... 09 10 11 12
... 99 100 101.
A format token A generates the sequence A
B C ... Z AA AB AC....
A format token a generates the sequence a
b c ... z aa ab ac....
A format token i generates the sequence i
ii iii iv v vi vii viii ix x ....
A format token I generates the sequence I
II III IV V VI VII VIII IX X ....
Any other format token indicates a numbering sequence that
starts with that token. If an implementation does not support a
numbering sequence that starts with that token, it must use a format
token of 1.
When numbering with an alphabetic sequence, the lang
attribute specifies which language's alphabet is to be used; it has
the same range of values as xml:lang [XML];
if no lang value is specified, the language should be
determined from the system environment
The letter-value attribute disambiguates between
numbering sequences that use letters. In many languages there are two
commonly used numbering sequences that use letters. One numbering
sequence assigns numeric values to letters in alphabetic sequence, and
the other assigns numeric values to each letter in some other manner.
In English, these would correspond to the numbering sequences
specified by the format tokens a and i. In
some languages, the first member of each sequence is the same, and so
the format token alone would be ambiguous. A value of
alphabetic specifies the alphabetic sequence; a value of
other specifies the other sequence. If the
letter-value attribute is not specified, then it is
implementation-dependent how any ambiguity is resolved.
The grouping-separator attribute gives the separator
used as a grouping (e.g. thousands) separator in decimal numbering
sequences, and the optional grouping-size specifies the
size (normally 3) of the grouping. For example,
grouping-separator="," and grouping-size="3"
would produce numbers of the form 1,000,000. If only one
of the grouping-separator and grouping-size
attributes is specified, then it is ignored.
Here are some examples of conversion specifications:
format="ア" specifies Katakana
numbering
format="イ" specifies Katakana
numbering in the "iroha" order
format="๑" specifies numbering with
Thai digits
format="א" letter-value="other"
specifies "traditional" Hebrew numbering
format="ა" letter-value="other"
specifies Georgian numbering
format="α" letter-value="other"
specifies "classical" Greek numbering
format="а" letter-value="other"
specifies Old Slavic numbering
When the result has a known regular structure, it is useful to be
able to specify directly the template for selected nodes. The
xsl:for-each instruction contains a template, which is
instantiated for each node selected by the expression specified by the
select attribute. The select attribute is
required. The expression must evaluate to a node-set. The template
is instantiated with the selected node as the current node, and with a list of all
of the selected nodes as the current node list. The nodes are
processed in document order, unless a sorting specification is present
(see [10 Sorting]).
For example, given an XML document with this structure
<customers>
<customer>
<name>...</name>
<order>...</order>
<order>...</order>
</customer>
<customer>
<name>...</name>
<order>...</order>
<order>...</order>
</customer>
</customers>
the following would create an HTML document containing a table with
a row for each customer element
<xsl:template match="/">
<html>
<head>
<title>customers</title>
</head>
<body>
<table>
<tbody>
<xsl:for-each select="customers/customer">
<tr>
<th>
<xsl:apply-templates select="name"/>
</th>
<xsl:for-each select="order">
<td>
<xsl:apply-templates/>
</td>
</xsl:for-each>
</tr>
</xsl:for-each>
</tbody>
</table>
</body>
</html>
</xsl:template>
There are two instructions in XSLT which support conditional
processing in a template: xsl:if and
xsl:choose. The xsl:if instruction provides
simple if-then conditionality; the xsl:choose instruction
supports selection of one choice when there are several
possibilities.
xsl:if
The xsl:if element has a single attribute,
test which specifies an expression. The content is a template.
The expression is evaluated and the resulting object is converted to a
boolean as if by a call to the boolean function.
If the result is true, then the content template is instantiated;
otherwise, nothing is created. In the following example, the names in
a group of names are formatted as a comma separated list:
<xsl:template match="namelist/name"> <xsl:apply-templates/> <xsl:if test="not(position()=last())">, </xsl:if> </xsl:template>
The following colors every other table row yellow:
<xsl:template match="item">
<tr>
<xsl:if test="position() mod 2 = 0">
<xsl:attribute name="bgcolor">yellow</xsl:attribute>
</xsl:if>
<xsl:apply-templates/>
</tr>
</xsl:template>
xsl:choose
The xsl:choose element selects one among a number of
possible alternatives. It consists of a series of
xsl:when elements followed by an optional
xsl:otherwise element. Each xsl:when
element has a single attribute, test, which specifies an
expression. The content of the
xsl:when and xsl:otherwise elements is a
template. When an xsl:choose element is processed, each
of the xsl:when elements is tested in turn, by evaluating
the expression and converting the resulting object to a boolean as if
by a call to the boolean function. The content
of the first, and only the first, xsl:when element whose
test is true is instantiated. If no xsl:when is true,
the content of the xsl:otherwise element is
instantiated. If no xsl:when element is true, and no
xsl:otherwise element is present, nothing is created.
The following example enumerates items in an ordered list using arabic numerals, letters, or roman numerals depending on the depth to which the ordered lists are nested.
<xsl:template match="orderedlist/listitem">
<fo:list-item indent-start='2pi'>
<fo:list-item-label>
<xsl:variable name="level"
select="count(ancestor::orderedlist) mod 3"/>
<xsl:choose>
<xsl:when test='$level=1'>
<xsl:number format="i"/>
</xsl:when>
<xsl:when test='$level=2'>
<xsl:number format="a"/>
</xsl:when>
<xsl:otherwise>
<xsl:number format="1"/>
</xsl:otherwise>
</xsl:choose>
<xsl:text>. </xsl:text>
</fo:list-item-label>
<fo:list-item-body>
<xsl:apply-templates/>
</fo:list-item-body>
</fo:list-item>
</xsl:template>
Sorting is specified by adding xsl:sort elements as
children of xsl:apply-templates or
xsl:for-each. The first xsl:sort child
specifies the primary sort key, the second xsl:sort child
specifies the secondary sort key and so on. When
xsl:apply-templates or xsl:for-each has one
or more xsl:sort children, then instead of processing the
selected elements in document order, it sorts the elements according
to the specified sort keys and then processes them in sorted order.
When used in xsl:for-each, xsl:sort elements
must occur first. When a template is instantiated by
xsl:apply-templates and xsl:for-each, the
current node list consists of the complete list of nodes being
processed in sorted order.
xsl:sort has a select attribute whose
value is an expression. For
each node to be processed, the expression is evaluated with that node
as the current node. The resulting object is converted to a string as
if by a call to the string function; this string
is used as the sort key for that node. The default value of the
select attribute is ., which will cause the
string-value of the current node to be used as the sort key.
This string serves as a sort key for the node. The following
optional attributes on xsl:sort control how the list of
sort keys are sorted:
order specifies whether the strings should be
sorted in ascending or descending order; ascending
specifies ascending order; descending specifies
descending order; the default is ascending
lang specifies the language of the sort keys; it
has the same range of values as xml:lang [XML]; if no lang value is specified, the
language should be determined from the system environment
data-type specifies the data type of the
strings; the following values are allowed
text specifies that the sort keys should be
sorted lexicographically in the culturally correct manner for the
language specified by lang
number specifies that the sort keys should be
converted to numbers and then sorted according to the numeric value;
the value specified by lang can be used to assist in the
conversion to numbers; leading and trailing whitespace should be
ignored when converting the sort keys to numbers
The default value is text.
NOTE: The XSL Working Group plans that future versions of XSLT will leverage XML Schemas to define further values for this attribute.
case-order has the value
upper-first or lower-first; this applies
when data-type="text", and specifies that upper-case
letters should sort before lower-case letters or vice-versa
respectively. For example, if lang="en", then A a B
b are sorted with case-order="upper-first" and
a A b B are sorted with
case-order="lower-first". The default value is language
dependent.
The values of all of the above attributes are interpreted as attribute value templates.
NOTE: It is recommended that implementers consult [UNICODE TR10] for information on internationalized sorting.
The sort must be stable: in the sorted list of nodes, any sub list that has sort keys that all compare equal must be in document order.
For example, suppose an employee database has the form
<employees>
<employee>
<name>
<first>James</first>
<last>Clark</last>
</name>
...
</employee>
</employees>
Then a list of employees sorted by name could be generated using:
<xsl:template match="employees">
<ul>
<xsl:apply-templates select="employee">
<xsl:sort select="name/last"/>
<xsl:sort select="name/first"/>
</xsl:apply-templates>
</ul>
</xsl:template>
<xsl:template match="employee">
<li>
<xsl:value-of select="name/first"/>
<xsl:text> </xsl:text>
<xsl:value-of select="name/last"/>
</li>
</xsl:template>
A variable is a name that may be bound to a value. The value to
which a variable is bound (the value of the variable) can
be an object of any of the types that can be returned by expressions.
There are two elements that can be used to bind variables:
xsl:variable and xsl:param. The difference
is that the value specified on the xsl:param variable is
only a default value for the binding; when the template or stylesheet
within which the xsl:param element occurs is invoked,
parameters may be passed that are used in place of the default
values.
Both xsl:variable and xsl:param have a
required name attribute, which specifies the name of the
variable. The value of the name attribute is a QName, which is expanded as described
in [2.4 Qualified Names].
For any use of these variable-binding elements, there is a region of the stylesheet tree within which the binding is visible; within this region any binding of the variable that was visible on the variable-binding element itself is hidden. Thus, only the innermost binding of a variable is visible. The set of variable bindings in scope for an expression consists of those bindings that are visible at the point in the stylesheet where the expression occurs.
Variables introduce an additional data-type into the expression
language. This additional data type is called result tree
fragment. A variable may be bound to a result tree fragment
instead of one of the four basic XPath data-types (string, number,
boolean, node-set). A result tree fragment represents a fragment of
the result tree. A result tree fragment is treated equivalently to a
node-set that contains just a single root node. However, the
operations permitted on a result tree fragment are a subset of those
permitted on a node-set. An operation is permitted on a result tree
fragment only if that operation would be permitted on a string (the
operation on the string may involve first converting the string to a
number or boolean). In particular, it is not permitted to use the
/, //, and [] operators on
result tree fragments. When a permitted operation is performed on a
result tree fragment, it is performed exactly as it would be on the
equivalent node-set.
When a result tree fragment is copied into the result tree (see
[11.3 Using Values of Variables and Parameters with
xsl:copy-of]), then all the nodes that are children of the
root node in the equivalent node-set are added in sequence to the
result tree.
Expressions can only return values of type result tree fragment by referencing variables of type result tree fragment or calling extension functions that return a result tree fragment or getting a system property whose value is a result tree fragment.
A variable-binding element can specify the value of the variable in three alternative ways.
If the variable-binding element has a select
attribute, then the value of the attribute must be an expression and the value of the variable
is the object that results from evaluating the expression. In this
case, the content must be empty.
If the variable-binding element does not have a select
attribute and has non-empty content (i.e. the variable-binding element
has one or more child nodes), then the contents of the
variable-binding element specifies the value. The contents of the
variable-binding element is a template, which is instantiated to give
the value of the variable. The value is a result tree fragment
equivalent to a node-set containing just a single root node having as
children the sequence of nodes produced by instantiating the
template.
It is an error if the sequence of nodes produced by instantiating the template includes an attribute node or a namespace node, since a root node cannot have an attribute node or a namespace node as a child. An XSLT processor may signal the error; if it does not signal the error, it must recover by not adding the attribute node or namespace node.
If the variable-binding element has empty content and does not have
a select attribute, then the value of the variable is an
empty string. Thus
<xsl:variable name="x"/>
is equivalent to
<xsl:variable name="x" select="''"/>
NOTE: When a variable is used to select nodes by position, be careful not to do:<xsl:variable name="n">2</xsl:variable> ... <xsl:value-of select="item[$n]"/>This will output the value of the first item element, because the variablenwill be bound to a result tree fragment, not a number. Instead, do either<xsl:variable name="n" select="2"/> ... <xsl:value-of select="item[$n]"/>or<xsl:variable name="n">2</xsl:variable> ... <xsl:value-of select="item[position()=$n]"/>
xsl:copy-of
The xsl:copy-of element can be used to insert a result
tree fragment into the result tree, without first converting it to a
string as xsl:value-of does (see [7.6.1 Generating Text with xsl:value-of]). The required select attribute
contains an expression. When
the result of evaluating the expression is a result tree fragment, the
complete fragment is copied into the result tree. When it is
node-set, all the nodes in the set together with their content are
copied in document order over into the result tree. When it is of any
other type, the result is converted to a string and then inserted into
the result tree, as with xsl:value-of.
Both xsl:variable and xsl:param are
allowed as top-level elements.
A top-level variable-binding element declares a global variable that
is visible everywhere. A top-level xsl:param element
declares a parameter to the stylesheet; XSLT does not define the
mechanism by which parameters are passed to the stylesheet. It is an
error if a stylesheet contains more than one binding of a top-level
variable with the same name and same import precedence. At the
top-level, the expression or template specifying the variable value is
evaluated with the same context as that used to process the root node
of the source document: the current node is the root node of the
source document and the current node list is a list containing just
the root node of the source document. If the template or expression
specifying the value of a global variable x references a
global variable y, then the value for y must
be computed before the value of x. It is an error if it
is impossible to do this for all global variable definitions, in other
words it is an error if the definitions are circular.
This example declares a global variable para-font-size,
which it references in an attribute value template.
<xsl:variable name="para-font-size">12pt</xsl:variable>
<xsl:template match="para">
<fo:block font-size="{$para-font-size}">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
As well as being allowed at the top-level, both
xsl:variable and xsl:param are also
allowed in templates. xsl:variable is allowed