0% found this document useful (0 votes)
44 views24 pages

XSLT

The document discusses the key elements of XSLT including xsl:stylesheet, xsl:transform, xsl:template, xsl:apply-templates, xsl:element, xsl:attribute, xsl:value-of, xsl:output, xsl:text, xsl:comment, xsl:message, xsl:number, and xsl:if. It provides details on attributes and usage of each element.

Uploaded by

Omkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views24 pages

XSLT

The document discusses the key elements of XSLT including xsl:stylesheet, xsl:transform, xsl:template, xsl:apply-templates, xsl:element, xsl:attribute, xsl:value-of, xsl:output, xsl:text, xsl:comment, xsl:message, xsl:number, and xsl:if. It provides details on attributes and usage of each element.

Uploaded by

Omkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

 XSLT 2.

0
o Introduction
o Elements
 XAPTH 2.0
o Introduction
o XPath Terminology
o Expression
o Operators
o Axes
o Function Library
 Regular Expression
 Important URLs
XSLT
Introduction

XSL stands for “Extensible Stylesheet Language”, which consists of three parts—

XSLT (XSL Transformation) — for transforming xml documents


XPATH — for navigating xml documents
XSL-FO — for formatting xml documents

To connect XSL in the XML file use the below syntax—

<?xml:stylesheet type=“text/xsl” href=“b.xsl”?>


Elements

1. <xsl:stylesheet>
Definition: Defines the root element of a style sheet.

Attribute Usage Description


version Required

2. <xsl:transform>
Definition: Defines the root element of a style sheet.

3. <xsl:template>
Definition: Rules to apply when a specified node is matched. The type of node to be processed is identified by a
pattern, written in the mandatory match attribute. The following examples show some of the possibilities:

Pattern Meaning

/ Matches the document node

XXX Matches any element whose name (tag) is XXX

* Matches any element

XXX/YYY Matches any YYY element whose parent is an XXX

XXX//YYY Matches any YYY element that has an ancestor named XXX

/*/XXX Matches any XXX element that is immediately below the root
(document) element

*[@ID] Matches any element with an ID attribute

XXX[1] Matches any XXX element that is the first XXX child of its parent
element. (Note that this kind of pattern can be very inefficient: it is
better to match all XXX elements with a single template, and then use
xsl:if to distinguish them)

SECTION[TITLE="Contents"] Matches any SECTION element whose first TITLE child element has the
value "Contents"

A/TITLE | B/TITLE | C/TITLE Matches any TITLE element whose parent is of type A or B or C

text() Matches any character data node

@* Matches any attribute

Attribute Usage Description


match Required —Used to associate a template with an xml element.
—Used to define a template for the entire xml document
—Value of match attribute is an XPATH expression.
name Optional If this is present, the template may be invoked directly using
xsl:call-template.
The match attribute then becomes optional.
mode Optional If this is present, the template will only be matched when the
same mode is used in the invoking xsl:apply-templates element.
priority Optional If there are several xsl:template elements that all match the
same node, the one that is chosen is determined by the optional
priority attribute: the template with highest priority wins. The
priority is written as a floating-point number; the default priority
is 1. If two matching templates have the same priority, the one
that appears last in the stylesheet is used.

4. <xsl:apply-templates>
Definition: Applies a template rule to the current element or to the current element's child nodes.

Attribute Usage Description


select Optional 1. If the select attribute is omitted, apply-templates causes all the
immediate children of the current node to be processed:
2. If the select attribute is included, the result must be a sequence of
nodes. All nodes selected by the expression are processed.
mode Optional Identifies the processing mode. If this attribute is present, only
templates with a matching mode parameter will be considered.

5. <xsl:element>
Definition: Creates an element node in the output document

Attribute Usage Description


name Required It gives the name of the generated element.

6. <xsl:attribute>
Definition: Adds an attribute. The attribute must be output immediately after the element.

Attribute Usage Description


name Required It gives the name of the generated attribute.

7. <xsl:value-of>
Definition: Extracts the value of a selected node

8. <xsl:output>
Definition: Defines the format of the output document. It is always a top-level element.

Attribute Usage Description


version Optional Determines the version of XML or HTML to be output. Currently this is
documentary only.
standalone Optional This is used only for XML output: if it is present, a standalone attribute is
included in the XML declaration, with the value "yes" or "no"
omit-xml-declaration Optional The values are "yes" or "no". For XML output this controls whether an
xml declaration should be output; the default is "no".
indent Optional Values "yes" or "no" are accepted.

method Optional Following four possible values are:


xml — For XML Output
html — For HTML Output
xhtml — For XHTML Output
text — For TEXT Output
include-content-type Optional Values "yes" or "no" are accepted. The default is "yes".
This affects HTML output only. It controls whether a meta tag is
inserted into the HTML head element.
doctype-system Optional This is used only for XML output: it is copied into the DOCTYPE
declaration as the system identifier
doctype-public Optional This is used only for XML output: it is copied into the DOCTYPE
declaration as the public identifier. It is ignored if there is no system
identifier.
encoding Optional A character encoding, e.g. iso-8859-1 or utf-8. The value must be one
recognised both by the Java run-time system and by Saxon itself: the
encoding names that Saxon recognizes are ASCII, US-ASCII, iso-8859-
1, utf-8, utf8, cp1251. The default is UTF-8.
use-character-maps Optional To give the name character Map.

cdata-section-elements Optional This is used only for XML output. It is a whitespace-separated list of
element names. Character data belonging to these output elements will
be written within CDATA sections.

9. <xsl:text>
Definition: Writes literal text to the output. It allows white space to the output.

Attribute Usage Description


disable-output-escaping Optional Values "yes" or "no" are accepted. The default value is “no”. If set to
"yes", special characters such as "<" and "&" will be output as
themselves, not as entities.

10.<xsl:comment>
Definition: Creates a comment node in the result tree.

11.<xsl:message>
Definition: Writes a message to the output (used to report errors).

Attribute Usage Description


terminate Optional Values "yes" or "no" are accepted. The default value is “no”. If the value is
set to yes, processing of the stylesheet is terminated after issuing the
message.

12.<xsl:number>
Definition: Determines the integer position of the current node and formats a number

13.<xsl:if>
Definition: Contains a template that will be applied only if a specified condition is true.

Attribute Usage Description


test Required Value of “test” expression is a Boolean expression. The contents of the
xsl:if element are expanded only of the expression is true.

14.<xsl:choose>
Definition: Used in conjunction with <when> and <otherwise> to express multiple conditional tests.
It is used to choose one of a number of alternative outputs.
The element typically contains a number of xsl:when elements, each with a separate test condition.
The first xsl:when element whose condition matches the current element in the source document is
expanded, the others are ignored. If none of the conditions is satisfied, the xsl:otherwise child
element, if any, is expanded.

15.<xsl:when>
Definition: It is used within an <xsl:choose> element to indicate one of a number of choices.

Attribute Usage Description


test Required Value of “test” expression is a Boolean expression. The contents of the
xsl:when element are expanded only of the expression is true.

16.<xsl:otherwise>
Definition: The <xsl:otherwise> element is used within an <xsl:choose> element to indicate the
default action to be taken if none of the other choices matches.

17.<xsl:for-each>
Definition: Allows iteration in XSLT.

Attribute Usage Description


select Required Defines the nodes over which the statement will iterate

18.<xsl:sort>
Definition: used to sort the output. The xsl:sort element is used within an xsl:for-each or xsl:apply-
templates element to indicate the order in which the selected elements are processed.

Attribute Usage Description


select Optional It is a string expression that calculates the sort key.

order Optional Possible values "ascending" or "descending"

data-type Optional Possible values "text" or "number"

case-order Optional Possible values "upper-first" and "lower-first"

19.<xsl:analyze-string>
Definition: The <xsl:analyze-string> element is new in XSLT 2.0.
It applies a regular expression to a supplied string value. The string is split into a sequence of
substrings, each of which is classified as either a matching substring (if it matches the regular
expression) or a non-matching substring (if it doesn't). The substrings are then processed individually:
the matching substrings by a <xsl:matching-substring> element that appears as a child of the
<xsl:analyze-string> instruction, the non-matching substrings by a similar <xsl:non-matching-
substring> element. If either of these is omitted, the relevant substrings are not processed.

When processing matching substrings, it is possible to call the regex-group() function to find the
parts of the matching substring that matched particular parenthesized groups within the regular
expression.

Attribute Usage Description


select Required ‘select’ is an XPath expression whose value is the string to be
analyzed
regex Required ‘regex’ is the regular expression

flags Optional Possible values are i, m, s, x


i — Case insensitive
m — Multiline
s — To indicate that the dot (.) character matches every
character, including the newline (x0A) character
x — Ignore whitespace from regex

20.<xsl:matching-substring>
Definition: It is used within an <xsl:analyze-string> element to indicate the default action to be
taken with substrings that match a regular expression.

21.<xsl:non-matching-substring>
Definition: It is used within an <xsl:analyze-string> element to indicate the default action to be
taken with substrings that do not match a regular expression.

22.<xsl:strip-space>
Definition: It is used at the top level of the stylesheet to define elements in the source document for
which white-space nodes are insignificant and should be removed from the tree before processing.
Attribute Usage Description
element Required Defines a space-separated list of element names.
The value "*" may be used to mean "all elements"; in this case any
elements where whitespace is not to be stripped may be indicated by
an <xsl:preserve-space> element.

23.<xsl:preserve-space>
Definition: It is used at the top level of the stylesheet to define elements in the source document for
which white-space nodes are significant and should be retained

Attribute Usage Description


element Required Defines a space-separated list of element names. The value "*" may be
used to mean "all elements"; in this case any elements where
whitespace is not to be preserved may be indicated by an <xsl:strip-
space element>.

24.<xsl:copy>
Definition: Creates a copy of the current node (without child nodes and attributes). The actual effect
depends on whether the node is an element, an attribute, or a text node.
For an element, the start and end element tags are copied; the attributes, character content and child
elements are copied only if xsl:apply-templates is used within xsl:copy.

The following example is a template that copies the input element to the output, together with all its
child elements, character content, and attributes:
<xsl:template match="*|text()|@*">
<xsl:copy>
<xsl:apply-templates select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>

25.<xsl:copy-of>
Definition: Creates a copy of the current node (with child nodes and attributes)

Attribute Usage Description


select Required Copies of the value of the expression in the select attribute to the result
tree
copy-namespaces Optional Possible values are “Yes” or “No”. The default is "yes”

26.<xsl:attribute-set>
Definition: Defines a named set of attributes. An attribute-set contains a collection of xsl:attribute
elements.
They can be added to an element by specifying use-attribute-sets in the list of attributes for the
element. The value is a space-separated list of attribute-set names.

Attribute Usage Description


name Required To give the name of attribute set.

use-attribute-sets Optional To import other attributes from other attribute set.

27.<xsl:call-template>
Definition: Calls a named template

Attribute Usage Description


name Required Must match the name defined on an xsl:template element.
28.<xsl:variable>
Definition: Declares a local or global variable

Attribute Usage Description


name Required Defines the name of the variable.

select Optional value of the variable may be defined either by an expression within the
select attribute or by the contents of the xsl:variable element
as Optional Define the type of the variable

29.<xsl:param>
Definition: Declares a local or global parameter (formal parameter) to a template. As a template
parameter, it must be used as an immediate child of the xsl:template element. As a stylesheet
parameter, it must be used as an immediate child of the xsl:stylesheet element.

Attribute Usage Description


name Required Defines the name of the parameter.

select Optional Value of the parameter may be defined either by an expression within
the select attribute or by the contents of the xsl:param element.
The default value is ignored if an actual parameter is supplied with the
same name.
as Optional Define the type of the param

30.<xsl:with-param>
Definition: Defines the value of a parameter (actual parameter) to be passed into a template. It may
be used within an xsl:call-template, xsl:apply-templates, xsl:apply-imports, or xsl:next-match

Attribute Usage Description


name Required Defines the name of the parameter.

select Optional Value of the parameter may be defined either by an expression within
the select attribute or by the contents of the xsl:param element.

The parameter has no effect unless the called template includes a matching xsl:param element.

31.<xsl:apply-imports>
Definition: Applies a template rule from an imported style sheet.
The effect is to search for a template that matches the current node and that is defined in a stylesheet
that was imported (directly or indirectly, possibly via xsl:include) from the stylesheet containing the
current template, and whose mode matches the current mode. If there is such a template, it is
activated using the current node. If not, the call on xsl:apply-imports has no effect.

32.<xsl:next-match>
Definition: It is very similar to xsl:apply-imports, but with a different algorithm for choosing the next
template to execute. It chooses the template rule that matches the current node and that would have
been chosen if the current template rule and all higher precedence/priority rules were not there.

33.<xsl:import>
Definition: Imports the contents of one style sheet into another.
Note: An imported style sheet has lower precedence than the importing style sheet

Attribute Usage Description


href Required URL of another style sheet

34.<xsl:include>
Definition: Includes the contents of one style sheet into another.
Note: An included style sheet has the same precedence as the including style sheet

Attribute Usage Description


href Required URL of another style sheet

35.<xsl:processing-instruction>
Definition: Writes a processing instruction to the output and can appear anywhere within an
xsl:template.

Attribute Usage Description


name Required Gives the name of the PI

36.<xsl:for-each-group>
Definition: The xsl:for-each-group element selects a sequence of nodes and/or atomic values and
organizes them into subsets called groups. There are four possible ways of defining the grouping:

group-by: This groups together all items having the same value for a grouping key. The grouping key
may have multiple values (a sequence of values) in which case the item is added to more than one
group.

group-adjacent: This groups together all items having the same value for a grouping key, provided
that they are also adjacent in the input sequence. This is useful when you need to wrap a new element
around a sequence of related elements in the source documents, for example a consecutive sequence
of <bullet> elements. In this case the grouping key must be single-valued.

group-starting-with: This processes the items in the supplied sequence in turn, starting a new group
whenever one of the items matches a specified pattern. This is useful, for example, when matching an
<h2> element and its following <p> elements.

group-ending-with: This processes the items in the supplied sequence in turn, closing the current
group whenever one of the items matches a specified pattern. This is useful when matching a
sequence of items in which the last item in the group carries some distinguishing attribute such as
continued="no".

37.<xsl:function>
Definition: The xsl:function element defines a function within a stylesheet. The function is written in
XSLT but it may be called from any XPath expression in the stylesheet. It must have a non-default
namespace prefix.

Attribute Usage Description


name Required Gives the name of the Function

Example—
<xsl:function name="my:factorial" as="xs:integer">
<xsl:param name="number" as="xs:integer"/>
<xsl:sequence select="if ($number=0) then 1 else $number * my:factorial($number-1)"/>

38.<xsl:key>
Definition: Declares a named key that can be used in the style sheet with the key() function
Attribute Usage Description
name Required Gives the name of the Key

match Required Determines which nodes in the source document will be matched

use Optional Specifies the criteria which decides whether the node matches or not

39.<xsl:result-document>
Definition: It is new in XSLT 2.0. It is used to output its contents to a file.

Attribute Usage Description


href Optional Gives the URI for the result document

method Optional Following four possible values are:


xml — For XML Output
html — For HTML Output
xhtml — For XHTML Output
text — For TEXT Output

40.<xsl:character-map>
Definition: It must be a child of xsl:stylesheet and it contains one or more xsl:output-characters. The
character specifies the original character which is replaced by the value of attribute string.

Attribute Usage Description


name Required Gives the name of char-map

Example:
<xsl:character-map name="char-map">
<xsl:output-character character="ù" string="&amp;#x00F9;"/>
<xsl:output-character character="ú" string="&amp;#x00FA;"/>
</xsl:character-map>

41.<xsl:sequence>
Definition: It is used to construct arbitrary sequences. It may select any sequence of nodes and/or
atomic values, and essentially adds these to the result sequence.

Attribute Usage Description


select Optional The input may be specified either by a select attribute, or by the
instructions contained in the xsl:sequence instruction, or both (the
select attribute is processed first).
as Optional It used to define the required type of the sequence.

Example:
(1)
<e>
<xsl:sequence select="1 to 5"/>
<br/>
<xsl:sequence select="6 to 10"/>
</e>
(2)
<xsl:variable name="seq" as="xs:integer *">
<xsl:for-each select="1 to 5">>
<xsl:sequence select=". * ."/>
</xsl:for-each/>
</xsl:variable>
(3)
<xsl:variable name="seq" as="attribute() *">
<xsl:attribute name="a">10</xsl:attribute>
<xsl:attribute name="b">20</xsl:attribute>
<xsl:attribute name="a">30</xsl:attribute>
</xsl:variable>

42.<xsl:decimal-format>
Definition: Defines the characters and symbols to be used when converting numbers into strings, with
the format-number() function

43.<xsl:fallback>
Definition: Specifies an alternate code to run if the processor does not support an XSLT element

44.<xsl:namespace-alias>
Definition: Replaces a namespace in the style sheet to a different namespace in the output

45.<xsl:import-schema>
Definition:

46.<xsl:namespace>
Definition:

47.<xsl:sort-key>
Definition:

48.<xsl:perform-sort>
Definition:
XPATH
Introduction

— XPath is a language for finding information in an XML document.


— XPath uses path expressions to navigate through elements and attributes in an XML document.
— XPath is a major element in XSLT
— XPath is a W3C recommendation
— XQuery and XPointer are both built on XPath expressions.
— XPath contains a library of standard functions
— XPath 1.0 became a Recommendation on 16 November 1999
— XPath 2.0 is the current version of the language; it became a Recommendation on 23 January 2007

XPath Terminology

 Nodes
 Atomic values
 Items
 Parent
 Children
 Siblings
 Ancestors
 Descendants

Nodes— In XPath, there are seven kinds of nodes—


1. document
2. element
3. attribute
4. text
5. namespace
6. processing-instruction
7. comment

Look at the following XML document:

<?xml version="1.0" encoding="ISO-8859-1"?>


<!-- bookstore Details -->
<bookstore xmlns:bk="http://abc.xyz.org">
<?pb number="17"?>
<book>
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>

Example of nodes in the XML document above:

<bookstore> (document node)


<author>J K. Rowling</author> (element node)
lang="en" (attribute node)
2005 (text node)
xmlns:bk="http://abc.xyz.org" (namespace node)
<?pb number="17"?> (processing instruction node)
<!-- bookstore Details --> (comment node)
Atomic values: Atomic values are nodes with no children or parent. Ex.

J K. Rowling
"en"

Items: Items are atomic values or nodes.

Parent: Each element and attribute has one parent.

Children: Element nodes may have zero, one or more children.

Siblings: Nodes that have the same parent.

Ancestors: A node's parent, parent's parent, etc.

Descendants: A node's children, children's children, etc.

Expression
Three Forms of XPath Expressions are
 Path Expression— expression1/expression2
 Predicate Expression— expression1[expression2]
 Union Expression— expression1 | expression2

Path Expression (Selecting Nodes)—

Expression Description
nodename Selects all child nodes of the named node
/ Selects from the root node
// Selects nodes in the document from the current node that match the selection no matter where they are
. Selects the current node
.. Selects the parent of the current node
@ Selects attributes

Examples

Path Expression Result


bookstore Selects all the child nodes of the bookstore element
/bookstore Selects the root element bookstore

Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!
bookstore/book Selects all book elements that are children of bookstore
//book Selects all book elements no matter where they are in the document
bookstore//book Selects all book elements that are descendant of the bookstore element, no matter where they are under
the bookstore element
//@lang Selects all attributes that are named lang

Predicates
Predicates are used to find a specific node or a node that contains a specific value.
Predicates are always embedded in square brackets.
In the table below we have listed some path expressions with predicates and the result of the expressions:

Path Expression Result


/bookstore/book[1] Selects the first book element that is the child of the bookstore element.

Note: IE5 and later has implemented that [0] should be the first node, but according to
the W3C standard it should have been [1]!!
/bookstore/book[last()] Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore element
//title[@lang] Selects all the title elements that have an attribute named lang
//title[@lang='eng'] Selects all the title elements that have an attribute named lang with a value of 'eng'
/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price element with a
value greater than 35.00
/bookstore/book[price>35.00]/title Selects all the title elements of the book elements of the bookstore element that have a
price element with a value greater than 35.00

Selecting Unknown Nodes


XPath wildcards can be used to select unknown XML elements.

Wildcard Description
* Matches any element node
@* Matches any attribute node
node() Matches any node of any kind

In the table below we have listed some path expressions and the result of the expressions:

Path Expression Result


/bookstore/* Selects all the child nodes of the bookstore element
//* Selects all elements in the document
//title[@*] Selects all title elements which have any attribute

Selecting Several Paths


By using the | operator in an XPath expression you can select several paths.
In the table below we have listed some path expressions and the result of the expressions:

Path Expression Result


//book/title | //book/price Selects all the title AND price elements of all book elements
//title | //price Selects all the title AND price elements in the document
/bookstore/book/title | //price Selects all the title elements of the book element of the bookstore element AND all the price
elements in the document

Location step consists of two required parts


1. an axis (defines the tree-relationship between the selected nodes and the current node)
2. a node test (identifies a node within an axis)
3. zero or more predicates (to further refine the selected node-set) (optional part)

XPATH Axes—
An axis defines a node-set relative to the current node.

Axis Name Result


ancestor Selects all ancestors (parent, grandparent, etc.) of the current node
ancestor-or-self Selects all ancestors (parent, grandparent, etc.) of the current node and the
current node itself
attribute Selects all attributes of the current node
child Selects all children of the current node
descendant Selects all descendants (children, grandchildren, etc.) of the current node
descendant-or-self Selects all descendants (children, grandchildren, etc.) of the current node
and the current node itself
following Selects everything in the document after the closing tag of the current node
following-sibling Selects all siblings after the current node
namespace Selects all namespace nodes of the current node
parent Selects the parent of the current node
preceding Selects everything in the document that is before the start tag of the current
node
preceding-sibling Selects all siblings before the current node
self Selects the current node
Axis and the node test are separated by "::"
The syntax for a location step is: axisname::nodetest[predicate]

Examples
Example Result
child::book Selects all book nodes that are children of the current node
attribute::lang Selects the lang attribute of the current node
child::* Selects all children of the current node
attribute::* Selects all attributes of the current node
child::text() Selects all text child nodes of the current node
child::node() Selects all child nodes of the current node
descendant::book Selects all book descendants of the current node
ancestor::book Selects all book ancestors of the current node
ancestor-or-self::book Selects all book ancestors of the current node - and the current as well if it is
a book node
child::*/child::price Selects all price grandchildren of the current node

XPath Operators

Operator Description Example Return value


| Computes two node-sets //book | //cd Returns a node-set with all book and cd elements
+ Addition 6+4 10
- Subtraction 6-4 2
* Multiplication 6*4 24
div Division 8 div 4 2
= eq Equal price eq 9.80 true if price is 9.80
false if price is 9.90
!= ne Not equal price ne 9.80 true if price is 9.90
false if price is 9.80
< lt Less than price lt 9.80 true if price is 9.00
false if price is 9.80
<= le Less than or equal to price le 9.80 true if price is 9.00
false if price is 9.90
> gt Greater than price gt 9.80 true if price is 9.90
false if price is 9.80
>= ge Greater than or equal to price ge 9.80 true if price is 9.90
false if price is 9.70
or or price=9.80 or price=9.70 true if price is 9.80
false if price is 9.50
and and price gt 9.00 and price lt true if price is 9.80
9.90 false if price is 8.50
mod Modulus (division remainder) 5 mod 2 1
except * except ccc
* except *[2]
* except (title | para)
Function library—

1. lower-case()
Description—To convert in the lower case.
lower-case(.)

2. upper-case()
Description—To convert in the upper case.
upper-case(.)

3. substring(string, start, len?)


Description—returns the substring of string starting with the character in start containing len (or all
trailing characters if last argument omitted)
substring('1234567890', 2, 5) returns '23456'
 The first two arguments of the substring function are mandatory. The third argument is
optional.
 If the third argument is omitted then the function will return all the characters from num1 to
the end of the string.
Select the first 20 characters of the first Para
substring(//Para[1], 1, 20)

Returns all characters from character 10 onward


substring(//Para[1], 10)

4. substring-before(string, sub-string)
Description—returns the characters in the string prior to the first occurrence of sub-string
substring-before(.,':')

5. substring-after(string, sub-string)
Description—returns the characters in the string after the first occurrence of sub-string
substring-after(.,':')

6. translate(‘original-String’, ‘characters to translate’, ‘replacement characters’)


translate(string1, string2, string3)
Description—locates all occurrences of the first character of string2 in string1 and replaces it with the
first character in string3, then repeats the process for the characters 2 through the length of string2
translate('hello','abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')

It will print HELLO

7. starts-with(string1, string2)
Description—returns true if string1 starts with string2
starts-with(bbb,ccc)
starts-with(.,'FILE')

8. ends-with(string1, string2)
Description—returns true if string1 ends with string2
starts-with(bbb,ccc)
starts-with(.,'FILE')

9. contains(string1, string2)
Description—returns true if string1 contains string2

Example Description
contains(//Para[1], 'SCRIPT') Does the first Para element contain the
string “SCRIPT”?
//node()[contains(., 'SCRIPT')] Select all nodes containing the string
“SCRIPT”
count(//node()[contains(., 'SCRIPT')]) Count the number of nodes containing the
string “SCRIPT”
count(/Playlist/Song)
count(//Title)

10. string-length(string?)
Description—returns a number containing the length of the argument string (or the length of the
string value of the current node if the argument is omitted)
string-length(//Para[1])

11. concat(string, string, string*)


Description—concatenates two or more strings together
concat('Name:', child::Name)
concat(ccc,' ',ddd,' ',eee)

12. normalize-space(string?)
Description—normalizes the space (collapses whitespace) of the string argument (or the current
node's string value if the string argument is omitted)
normalize-space()
normalize-space($x)

13.count(node-set)
Description—returns a number which counts how many nodes are in the argument

Example Description
count(//Para) Count the number of Para elements
count(//Para[@classification Count the number of Para elements with
='secret']) secret classification

14.sum(node-set)
Description—converts each node to a string then a number, then sums the numbers
sum(current-group())

15.avg()
Description—calculates average of all values of a sequence.

16.min()
Description—finds minimal value in a sequence

17.max()
Description—finds maximal value in a sequence

18.round(number)
Description—returns the integer closest to the number (by rounding)
round (2.3)
It will return 2

19.name(node-set?)
Description— returns name of currently processed elements or attributes. It include namespace also,
so use local-name() for the name only.
name()
name(/document/*[last()])

20.local-name(node-set?)
Description—returns the local name of the first node in the node-set (no prefix included)

21.position()
Description—returns the position of the current node in the current context
member[position() = 2]

22.last()
Description—returns the size of the current context

23.current()
Description—returns a node-set containing the current node as its only member

24.format-number(number,string1,string2?)
Description—produces formatted numeric output, where string1 contains a format pattern and
string2 contains an optional decimal format

25.index-of(sequence, value)
Description—The index-of() function allows you to obtain the position of value in sequence.
index-of((1,3,5,7,9,11),7)
Output: 4

26.remove(sequence, position)
Description—The remove function enables you to remove a value at a specified position from a
sequence.
remove((1,3,5,7,9,11),4)
Output: (1,3,5,7,9,11)

27.insert-before(sequence, position,value)
Description—Returns the sequence plus a new value.
insert-before((1,3,5,7,9,11),2,15)
Output: (1,15,3,5,7,9,11)

28.reverse(sequence)
Description—This function reverses the items in sequence.
reverse (1 to 10)
Output: 10 9 8 7 6 5 4 3 2 1

29.current-dateTime()
Description—returns the current date and time

30.matches()
Description—matches() is used to find patterns specified by a regular expression in a string. If a
match is found the function returns boolean value "true" otherwise it returns "false".The default mode
of matches() search is case sensitive An optional flag "i" can be specified to indicate a case insensitive
searching.
Input: <aaa>How do you do?</aaa>

<xsl:template match="/aaa">
<xxx>
<xsl:value-of select="matches(.,'do\s+you')"/>
</xxx>
<yyy>
<xsl:value-of select="matches(.,'\S{6}')"/>
</yyy>
<zzz>
<xsl:value-of select="matches(.,'how','i')"/>
</zzz>
</xsl:template>

Output:
<xxx>true</xxx>
<yyy>false</yyy>
<zzz>true</zzz>
31.replace()
Description—The function replace() replaces a pattern given as the second argument by the third
one. The "i" flag given as the forth optional argument enables case insensitive replacement. If the
second argument does not match any pattern in the first one the first argument is returned.
(1)
Input:
<aaa>How do you do?</aaa>

<xsl:template match="/aaa">
<xxx>
<xsl:value-of select="replace(.,'o.','#')"/>
</xxx>
<yyy>
<xsl:value-of select="replace(.,'ho','QQQ','i')"/>
</yyy>
<zzz>
<xsl:value-of select="replace(.,'HHH','BFF')"/>
</zzz>
</xsl:template>
Output:
<xxx>H# d#y# d#</xxx>
<yyy>QQQw do you do?</yyy>
<zzz>How do you do?</zzz>
(2)
In the second argument brackets can be used to create substring which can be referred to in the third
argument using "$number" syntax. If the number following "$" in the third argument is higher then
number of brackets in the second one an empty string is used as the replacement. "$0" refers to the
whole matched string.
Input:
<aaa>111-222-33</aaa>
<xsl:template match="/aaa">
<xxx>
<xsl:value-of select="replace(.,'(\d+)-(\d+)-(\d+)','$3$2::$1')"/>
</xxx>
<yyy>
<xsl:value-of select="replace(.,'(\d+)-\d+-\d+','$3$2::$1')"/>
</yyy>
<zzz>
<xsl:value-of select="replace(.,'(\d+)-(\d+)-(\d+)','$0 --- $3/$1')"/>
</zzz>
</xsl:template>

Output:
<xxx>33222::111</xxx>
<yyy>::111</yyy>
<zzz>111-222-33 --- 33/111</zzz>
(3)
Characters which have special meaning in the second or third argument must be escaped using
backslash "\".
Input:
<aaa>111*222?33</aaa>
<xsl:template match="/aaa">
<xxx>
<xsl:value-of select="replace(.,'(\d+)\*(\d+)\?(\d+)','$2')"/>
</xxx>
<yyy>
<xsl:value-of select="replace(.,'(\d+).*(\d+)\S?(\d+)','\$$2')"/>
</yyy>
<zzz>
<xsl:value-of select="replace(.,'(\d+).*?(\d+).*?(\d+)','\$$1\\\$$2\\\\\$$3')"/>
</zzz>
</xsl:template>

Output:
<xxx>222</xxx>
<yyy>$3</yyy>
<zzz>$111\$222\\$33</zzz>

32.tokenize()
Description—Function tokenize() creates text nodes from a string submitted as the first argument.
The second argument is a pattern which specifies separator between individual substrings. The
separators are not returned.
Input:
<aaa>How do you do</aaa>
<xsl:template match="/aaa">
<ul>
<xsl:for-each select="tokenize(.,'\s+')">
<li>
<xsl:value-of select="."/>
</li>
</xsl:for-each>
</ul>
</xsl:template>

Output:
<ul>
<li>How</li>
<li>do</li>
<li>you</li>
<li>do</li>
</ul>
Regular Expression

XPath 2.0 offers following three new functions that use regular expressions:
 tokenize()
 matches()
 replace()

\n A newline character.
. Any single character except \n.
[a-f] The lower-case letters a, f, or anything in that range.
\d Any numeric digit. The same as [0-9].
\s Any single whitespace character—a tab, carriage return linefeed, or spacebar space.
* After any of the symbols shown above, this means "zero or more characters fitting this description"
+ Like the asterisk, but meaning "one or more characters fitting this description."
? Like the asterisk, but meaning "zero or one character fitting this description."
{4} Like the asterisk, but meaning "four characters fitting this description." Because curly braces are
used in XSLT stylesheets to show which parts of an attribute value template are expressions to be
evaluated, be careful when using these in a regular expression specified in an attribute value:
escape the curly braces by repeating them (in this case, {{4}}) to tell an XSLT 2.0 processor not to
treat the curly braces as attribute value template expression delimiters.
\+ A literal plus sign. The backslash character escapes the character after it, telling the processor not
to treat it as a special regular expression character.
Important URLs

 http://kodlib.info/xsltckbk2-CHP-1-SECT-1.shtml
 http://kodlib.info/xsltckbk2-CHP-1-SECT-2.shtml
 http://www.xml.com/pub/a/2003/05/07/tr.html
 http://nwalsh.com/docs/tutorials/xsl/xsl/slides.html#conflict
 http://kodlib.info/xsltckbk2-CHP-6-SECT-7.shtml
 http://www.xml.com/pub/a/2003/06/04/tr.html
 http://saxon.sourceforge.net/saxon7.5/xsl-elements.html
 http://saxon.sourceforge.net/saxon7.5/expressions.html
 http://www.dpawson.co.uk/xsl/sect2/N6099.html
 http://www.xmlplease.com/xmltraining/xslt-by-example/examples/for-each-group_1.html
 http://www.w3.org/TR/xslt20/#regex-examples
 http://www.xmlplease.com/xmltraining/xslt-by-example/xslt-by-example.html
 http://www.regexbuddy.com/regex.html
 http://manual.macromates.com/en/regular_expressions
 http://zvon.org/
 http://mulberrytech.com/quickref/
 http://www.xmlplease.com/collection
OTHER

<xsl:value-of>—inserts the string value of an expression into the result tree.

1. <xsl:value-of select="3*."/> is used to get value of current node multiplied by 3.

2. <xsl:value-of select="1,2,3,4"/> will generate 1 2 3 4 if you see an space is inserted between each of
the value. And <xsl:value-of select="bbb[3],bbb[1],bbb[2]"/> if input xml is
<bbb>b1</bbb><bbb>b2</bbb><bbb>b3</bbb> then output will be b1 b2 b3.

3. Different types of values can be combined in a sequence.


<xsl:value-of select="bbb[2],12,'c',bbb[1]"/> gives b2 12 c b1 (if input xml is as per point 12).
<xsl:value-of select="1 to 3,12,'a',false(),14=14"/> gives 1 2 3 12 a false true.
<xsl:value-of select="-3 to 3"/> gives –3 –2 –1 0 1 2 3
<xsl:value-of select="1 to 3"/> gives 1 2 3

4. We can use for…in….return statement using sequence like


 <xsl:value-of select="for $a in (1 to 5) return $a * $a"/>
Output: 1 2 3 16 25
 <xsl:value-of select="for $a in reverse(('a','b','c')) return concat('x-',$a,'-y')"/>
Output: x-c-y x-b-y x-a-y
 <xsl:value-of select="for $a in bbb return $a * $a/@c"/>
if xml is as follows—
<aaa>
<bbb c="2">3</bbb>
<bbb c="5">8</bbb>
<bbb c="7">1</bbb>
</aaa>
Output: 9/2 64/5 1/7

5. Multidimensional for…in...return
 <xsl:value-of select="for $a in (1 to 3), $b in (1,10,100) return $a * $b"/>
Output: 1 10 100 2 20 200 ..etc.
 <xsl:value-of select="for $a in ('a','b'), $b in ('c','d'), $c in ('e','f','g') return concat($a,$b,$c)"/>
Output: ace acf acg ade adf adg bce bcf bcg bde bdf bdg

<xsl:for-each-group select=expression group-by=expression group-adjacent=expression group-starting-


with=pattern group-ending-with=pattern collation={uri}>
<!-- Content: (xsl:sort*, sequence-constructor) -->
</xsl:for-each-group>

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy