XSLT - built-in operations

 In XSLT, functions are built-in operations that let you manipulate data, navigate XML, or calculate values. They are primarily used inside XPath expressions. Let’s go through the most common ones in detail:


1. count()

  • Purpose: Returns the number of nodes in a node set.

  • Syntax: count(node-set)

  • Example:

<library>
  <book>1984</book>
  <book>Brave New World</book>
</library>

XSLT snippet:

<xsl:value-of select="count(library/book)"/>

Output:

2
  • Counts how many <book> elements exist under <library>.


2. string()

  • Purpose: Converts a node (or value) into a string.

  • Syntax: string(expression)

  • Example:

<book>
  <title>1984</title>
</book>

XSLT snippet:

<xsl:value-of select="string(title)"/>

Output:

1984
  • Ensures that the node value is treated as a string, useful when concatenating or comparing.


3. position()

  • Purpose: Returns the position of the current node in the context of a node-set (usually inside xsl:for-each).

  • Syntax: position()

  • Example:

<library>
  <book>1984</book>
  <book>Brave New World</book>
</library>

XSLT snippet:

<xsl:for-each select="library/book">
  <xsl:value-of select="position()"/>. <xsl:value-of select=".""/><br/>
</xsl:for-each>

Output:

1. 1984
2. Brave New World
  • Gives the sequential index of each <book> in the list.


4. Other Common Functions

Function Purpose Example
sum(node-set) Returns the sum of numeric values sum(library/book/price)
contains(string1, string2) Checks if string1 contains string2 contains(title, '1984')
concat(str1, str2, ...) Concatenates strings concat(title, ' by ', author)
substring(string, start, length?) Extracts a substring substring(title,1,4)"1984"
normalize-space(string) Removes leading/trailing spaces normalize-space(title)

5. Why Functions Are Important in XSLT

  • They transform and manipulate XML data without needing external scripts.

  • They allow for filtering, formatting, and calculations directly inside templates.

  • Functions work together with match and select to make XSLT powerful.


Example Combining Functions

<library>
  <book><title>1984</title><price>15</price></book>
  <book><title>Brave New World</title><price>20</price></book>
</library>

XSLT:

<xsl:for-each select="library/book">
  <xsl:value-of select="position()"/>. 
  <xsl:value-of select="concat(title, ' - $', price)"/><br/>
</xsl:for-each>
Total books: <xsl:value-of select="count(library/book)"/>

Output:

1. 1984 - $15
2. Brave New World - $20
Total books: 2

In short:

  • count() → counts nodes

  • string() → converts nodes to string

  • position() → finds node’s index

  • Other functions like sum(), concat(), contains() help with calculations, text processing, and filtering.