Nic Miloslav  
  Introduction to XSL  
  KEYWORDS       EXAMPLES       AUTHORS        ZVON      

There is now a complete XSLT reference and interactive X Lab

Introduction
Templates
Attributes
Axes
Repetition and sorting
Creation of elements and attributes
Conditional processing
Numbers generation and formatting
Variables
Numeric calculations
Boolean functions
String functions
Node set functions
Output
Copying
Miscellaneous Additional Functions
Combining Stylesheets
International

Introduction

Example 1: With XSL you can freely modify any source text. Stylesheet 1 and Stylesheet 2 produce different output from the same source file.

Example 5: Every XSL stylesheet must start with xsl:stylesheet element. The atribute version='1.0' xmlns:xsl specifies version of XSL(T) specification. This example shows the simplest possible stylesheet. As it does not contain any information, default processing is used.

Example 6: An XSL processors parses an XML source and tries to find a matching template rule. If it does, instructions inside matching template are evaluated.

Example 7: Contents of original elements can be recovered from original sources in two basic ways. Stylesheet 1 uses xsl:value-of construct. In this case the contents of the element is used without any further processing. Construct xsl:apply-templates in Stylesheet 2 is different. The parser further processes selected elements, for which a template is defined..

Templates

Example 6: An XSL processors parses an XML source and tries to find a matching template rule. If it does, instructions inside matching template are evaluated.

Example 72: Parts of XML document to which template should be applied are determined by location paths. The required syntax is specified in the XPath specification. Simple cases looks very similar to filesystem addressing. (Stylesheet 1)

Example 73: Processing always starts with template match="/" . This is the root element and its only child is document element, in our case xslTutorial. Many stylesheets do not contain this element explicitly. When an explicit template does not exist implicit template, which contains instruction is called. This instruction means: processes all of the children of the current node, including text nodes. Compare Stylesheet 1 and Stylesheet 2. When template for a node exists, there is no default processing (Stylesheet 3). If you want to include descendants of the node, you have to explicitly request their templates (Stylesheet 4).

Example 8: Template can match from selection of location paths, individual paths being separated with |.(Stylesheet 1). Wildcard * selects all possibilities.Compare Stylesheet 1 with Stylesheet 2. Compare with Example 73.

Example 4: // is very common in location paths. When it is used at the beginning of location path, it means: select all nodes in the document of the specified type. (Stylesheet 1). In the middle of a location path it means: select all nodes which appear in a node selected with the first part of location path. (Stylesheet 2

Example 71: Modes allow an element to be processed multiple times, each time producing a different result.In Stylesheet 2 one of the modes does not exist.

Example 69: Often several templates match selected element in XML source. It must be therefore decided which one to use. The templates are ordered according their priority which can be specified with priority attributte. If the template does not have this attribute, its priority is calculated according to several rules. Stylesheet 1 and Stylesheet 2 differ by priority of their templates. Stylesheet 3 shows the default action in the absence of priority attributes. Template CCC has lower priority than CCC/CCC, as it is less specific. Compare Stylesheet 4 and Stylesheet 5. Template CCC has lower priority than both CCC/CCC or AAA/CCC/CCC, but the latest two have the same priority. In such a case 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. In Stylesheet 6 less specific * has lower priority than CCC. Computed priorities ranges fromt -0.5 to 0.5. XSLT spec gives more details.

Attributes

Example 2: Attributes can be accessed in similar way as elements. Notice @ in front of attribute name.

Example 12: You can process an attribute in the same way as an element

Example 13: You can also select elements, which contain or do not contain the given attribute. Stylesheet 1 includes and Stylesheet 2 excludes an element based on the attribute

Axes

Example 58: Axes play a very important role in XSLT. Study following examples and click on the name of each axis to get some insight. Links to preceding and namespace axis does not work yet as they were not implemented in XT so far.Compare: child axis (Stylesheet 1), descendant axis (Stylesheet 2), parent axis (Stylesheet 3), ancestor axis (Stylesheet 4), following-sibling axis (Stylesheet 5), preceding-sibling axis (Stylesheet 6), following axis (Stylesheet 7), preceding axis (Stylesheet 8), attribute axis (Stylesheet 9), namespace axis (Stylesheet 10), self axis (Stylesheet 11), descendant-or-self axis (Stylesheet 12), ancestor-or-self axis (Stylesheet 13).

Example 27: All axes were used in this example.

Example 59: Axis child:: can be be omitted from a location step as it is the default axis. Axis attribute:: can be abbreviatet to @. // is short for /descendant-or-self::, . is short for self:: and .. is short for parent::.

Repetition and sorting

Example 74: The xsl:for-each instruction contains a template, which is applied to each node selected with select attribute.

Example 3: Nodes selected with xsl:for-each (Stylesheet 1 and Stylesheet 2) or xsl:apply-templates (Stylesheet 3) can be sorted. Order of sorting determines order attribute. Stylesheet 1 sorts in ascending and Stylesheet 2 in descending mode.

Example 14: Stylesheet 1 sorts in text and Stylesheet 2 in numeric mode. Notice the important difference. 2 is after 1 in alphabet so 2 goes after 10 in text mode.

Example 15: Stylesheet 1 sorts upercase and Stylesheet 2 lowercase letters first.

Creation of elements and attributes

Example 16: xsl:element generates elements in time of processing. Stylesheet 1 uses this feature, while Stylesheet 2 achieves the same effect in a different and laborous way.

Example 17: xsl:attribute generates elements in time of processing. It creates attribute in the element in which it is enclosed.

Example 10: Copy and copy-of constructs are used for nodes copying. Copy element copies only the current node without children and attributes, while copy-of copies everything.

Example 11: The xsl:copy element may have a use-attribute-sets attribute. In this way attributes for copied element can be specified. Stylesheet 2 does not work as expected (setting use-attribute-sets with name function)., because expresions in attributes that refer to named XSLT objects are not evaluated. Look at Example 31 for more details.

Conditional processing

Example 20: xsl:if instruction enables conditional processing. Stylesheet 1 demonstrates a typical case of xsl:for-each usage, adding a text between individual entries. Very often you do not want to add text after the last element. xsl-if construct comes handy here. (Stylesheet 2)

Example 22: xsl:choose element is used for selection between several possibilities.

Example 83: How to find out that some text starts with a number.

Numbers generation and formatting

Example 19: Stylesheet 1 demonstrates the default behaviour of xsl:number element. Numbering of individual chapter elements depends on position of the chapter element. Each level of chapters is numbered independently. Setting the attribute level into multiple in Stylesheet 2 enables more natural numbering.

Example 18: xsl:number inserts formated numbers into output. The format is given with format attribute. The attribute starts with format identificator followed by separator characters. Study individual stylesheets to compare notation.

Example 21: Stylesheet 1 and Stylesheet 2 are examples of formatting of multilevel numbers.

Variables

Example 33: Stylesheet 1 and Stylesheet 3 demonstrate different ways of setting xsl:variable, Stylesheet 2 and Stylesheet 4 of setting xsl:param.

Example 34: A stylesheet can contain several variables of the same name. Stylesheet 1 demonstrates a way how to recover the value of global variable which has the same name as a local one. The Stylesheet 2 demonstrates an incorrect approach. The value of local variable is bounded to xsl:when element. The rest of template therefore sees only the global variable.

Example 35: Parameters for a template can be passed with xsl:with-param element. If the template contains a xsl:param element with the same name as name attribute of xsl:with-param, this value is used. Stylesheet 1 shows a typical example. If you want to pass a variable, you have to define this variable with xsl:param element. Look at Stylesheet 2 for wrong approach.

Example 55: A variable can hold a result tree fragment. 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. Compare Stylesheet 1 and Stylesheet 2.

Example 82: There is an important difference in variable value specification.

Numeric calculations

Example 39: Functions number transforms its argument into a number. Stylesheet 1 demonstrates string conversion, Stylesheet 2 conversion of boolean values true and false.

Example 36: Addition, subtraction and multiplication uses common syntax (Stylesheet 1). Division syntax is less usual. Slash / is used in patterns and so keyword div is used instead (Stylesheet 2).Operator mod returns the remainder from a truncating division. (Stylesheet 2)

Example 37: Function sum() sums all numbers in selected nodes. Stylesheet 1 sums all numbers, Stylesheet 2 only odd ones.

Example 38: Functions ceilng(), floor() and round() transform floating point numbers into integers in the specified way.

Example 44: Function string() transforms its argument into string. This function is not usualy directly used in stylesheets as it is in most cases called by default. Stylesheet 1 shows examples of number to string conversions. Notice results of zero divisions.

Example 84: Test, if element value is a number

Boolean functions

Example 40: In Stylesheet 1 strings are arguments of boolean() function. A string is true if and only if its length is non-zero. In Stylesheet 2 is text transformed into numbers and then subjected to boolean() function. Stylesheet 3 compares "0" as a string and as a number.Stylesheet 4 uses node-sets as arguments for boolean() function.

Example 41: The not function returns true if its argument is false, and false otherwise.

Example 42: Functions true() and false() are useful, when some conditions are tested during programming.

Example 43: The lang function returns true or false depending on whether the language of the context node as specified by xml:lang attributes is the same as or is a sublanguage of the language specified by the argument string. The language of the context node is determined by the value of the xml:lang attribute on the context node, or, if the context node has no xml:lang attribute, by the value of the xml:lang attribute on the nearest ancestor of the context node that has an xml:lang attribute. If there is no such attribute, then lang returns false. If there is such an attribute, then lang returns true if the attribute value is equal to the argument ignoring case, or if there is some suffix starting with - such that the attribute value is equal to the argument ignoring that suffix of the attribute value and ignoring case.

String functions

Example 44: Function string() transforms its argument into string. This function is not usualy directly used in stylesheets as it is in most cases called by default. Stylesheet 1 shows examples of number to string conversions. Notice results of zero divisions.

Example 45: The concat function returns the concatenation of its arguments.

Example 46: The starts-with function returns true if the first argument string starts with the second argument string, and otherwise returns false. The contains function returns true if the first argument string contains the second argument string, and otherwise returns false.

Example 47: The substring-before function returns the substring of the first argument string that precedes and the substring-after function that follows the first occurrence of the second argument string in the first argument string. The substring function returns the substring of the first argument starting at the position specified in the second argument with length specified in the third argument. If the third argument is not specified, it returns the substring starting at the position specified in the second argument and continuing to the end of the string.Counting starts with 1. (Stylesheet 1). Stylesheet 2 demonstrates a situation where some arguments are out of range or they are not integrals. The returned substring contains those characters for which the position of the character is greater than or equal to the second argument and, if the third argument is specified, less than the sum of the second and third arguments.

Example 48: The string-length function returns the number of characters in the string. The normalize-space function returns the argument string with white space normalized by stripping leading and trailing whitespace and replacing sequences of whitespace characters by a single space.

Example 49: The translate function returns the first argument string with occurrences of characters in the second argument string replaced by the character at the corresponding position in the third argument string. If a character occurs more than once in second argument string, then the first occurrence determines the replacement character. If the third argument string is longer than the second argument string, then excess characters are ignored.

Node set functions

Example 50: The position function returns a number equal to the context position and the last function returns a number equal to the context size from the expression evaluation context.Stylesheet 1 demonstrates use of these functions in several contexts. Stylesheet 2 compares sorted and unsorted xsl:for-each element.

Example 51: The count function returns the number of nodes in the argument node-set.

Example 52: The id function selects elements by their unique ID. Stylesheet 1 shows simple examples of its use. Carefully study Stylesheet 2. Contents of title element is not displayed in [] as in DTD its attribute id is defined as CDATA, not ID. Several id's can be provided at once (Stylesheet 3).

Example 68: An example of id function usage.

Example 53: Functions name, local-name, and namespace-uri() are used to get informations about element and attribute names and namespaces.

Output

Example 54: The xsl:output element allows stylesheet authors to specify how they wish the result tree to be output. If an XSLT processor outputs the result tree, it should do so as specified by the xsl:output element; however, it is not required to do so. The xsl:output element is only allowed as a top-level element.Stylesheet 1 outputs as html and Stylesheet 2 as xml. Compare how empty tags are outputed.

Example 60: In the absence of xml:output element the default output method is xml (Stylesheet 1), but if document element of the output has value html (case insensitive) , then html method is used (Stylesheet 2).

Example 61: The html output method should not output an end-tag for empty elements specified in HTML specification.The html output method should not perform escaping for the content of the script and style elements (look at source of the lowest middle window in your browser) . Consult XSLT specification for more details.

Example 62: The encoding attribute specifies the preferred encoding to be used. The html output method should add a META element immediately after the start-tag of the HEAD element specifying the character encoding actually used. Stylesheet 1 outputs in UTF-8, Stylesheet 2 in UTF-16, and Stylesheet 3 in Cp1250. In Stylesheet 4 look at the source of the lowest middle window in your browser. The xml source contains characters which are not present in specified character set and they are therefore escaped.

Example 63: The text output method outputs the result tree by outputting the string-value of every text node in the result tree in document order without any escaping. Look at the source in your browser to see the output.

Copying

Example 10: Copy and copy-of constructs are used for nodes copying. Copy element copies only the current node without children and attributes, while copy-of copies everything.

Example 11: The xsl:copy element may have a use-attribute-sets attribute. In this way attributes for copied element can be specified. Stylesheet 2 does not work as expected (setting use-attribute-sets with name function)., because expresions in attributes that refer to named XSLT objects are not evaluated. Look at Example 31 for more details.

Miscellaneous Additional Functions

Example 56: The current function returns a node-set that has the current node as its only member. For an outermost expression (an expression not occurring within another expression), the current node is always the same as the context node. However, within square brackets the current node is usually different from the context node.

Example 57: Function generate-id generates id conforming to XML spec. Stylesheet 2 uses this function to add id to all elements in source XML.

Combining Stylesheets

Example 64: Other stylesheets can be imported (xsl:import) or included (xsl:include) into a stylesheet.. Importing a stylesheet is the same as including it except that definitions and template rules in the importing stylesheet take precedence over template rules and definitions in the imported stylesheet.Stylesheet 1 and Stylesheet 2 are imported or included into remaining xtylesheets. (NOTE: did XT right job with Stylesheet 9? SPEC: 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.)

Example 65: Stylesheet 3 imports Stylesheet 2 and Stylesheet 2 imports Stylesheet 1.

Example 66: Results of stylesheet combining depends on the position of xsl:include or xsl:import.

Example 67: You can use xsl:apply-imports element to get information from an imported template, whose behaviour you are changing. Stylesheet 2 imports Stylesheet 1 and overrides its template. Stylesheet 3 imports Stylesheet 1 and changes its template. xsl-apply-imports works only for templates imported with xsl:import, not for templates included with xsl:include.(Stylesheet 4

Example 70: Import precedence is more important than priority precedence. Look at Stylesheet 2.

International

Example 62: The encoding attribute specifies the preferred encoding to be used. The html output method should add a META element immediately after the start-tag of the HEAD element specifying the character encoding actually used. Stylesheet 1 outputs in UTF-8, Stylesheet 2 in UTF-16, and Stylesheet 3 in Cp1250. In Stylesheet 4 look at the source of the lowest middle window in your browser. The xml source contains characters which are not present in specified character set and they are therefore escaped.