XSLT Basic Syntax

XSLT Basic Syntax

XSLT 1.0 is a declarative programming language designed to transform XML documents into other formats, such as XML, HTML, CSV, or JSON. Its template-driven approach allows developers to define how data should be reorganized and outputted. In the Clevr Export Module, XSLT 1.0 is used to create export definitions for generating formatted outputs. This article introduces the basics of programming in XSLT, covering its structure, commonly used tags, conditional logic, and querying data.

XSLT Structure Overview

An XSLT stylesheet is itself an XML document that specifies the transformation rules. A basic XSLT stylesheet has the following structure:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  3.     <xsl:template match="/exportData">
  4.         <!-- Transformation logic here -->
  5.     </xsl:template>
  6. </xsl:stylesheet>
Key components:
  1. version: Specifies the version of XSLT (in this case, 1.0).
  2. xmlns:xsl: Declares the XSLT namespace.
  3. <xsl:template>: The building block for transformation rules. The match="/exportData" attribute specifies that this template matches the root node of the XML input.

Commonly Used XSLT Tags

Here are the essential tags you will use frequently in XSLT:

<xsl:template>

Defines reusable transformation rules. Templates can match specific nodes or be explicitly called using <xsl:call-template>.
  1. <xsl:template match="person">
  2.     <name>
  3.         <xsl:value-of select="name"/>
  4.     </name>
  5. </xsl:template>

<xsl:value-of>

Extracts and outputs the value of an XML element or attribute.
  1. <xsl:value-of select="person/age"/>

<xsl:text>

Outputs literal text in the transformation result. Useful for adding separators like commas or line breaks.
  1. <xsl:text>,</xsl:text>

<xsl:for-each>

Iterates over a set of nodes and applies transformation rules to each one.
  1. <xsl:for-each select="person">
  2.     <name>
  3.         <xsl:value-of select="name"/>
  4.     </name>
  5. </xsl:for-each>

<xsl:if>

Applies conditional logic to include or exclude elements based on a condition.
  1. <xsl:if test="age &gt; 18">
  2.     <adult>true</adult>
  3. </xsl:if>

<xsl:choose>, <xsl:when>, and <xsl:otherwise>

Used for multi-branch conditional logic.
  1. <xsl:choose>
  2.     <xsl:when test="age &lt; 13">
  3.         <category>child</category>
  4.     </xsl:when>
  5.     <xsl:when test="age &gt;= 13 and age &lt; 18">
  6.         <category>teenager</category>
  7.     </xsl:when>
  8.     <xsl:otherwise>
  9.         <category>adult</category>
  10.     </xsl:otherwise>
  11. </xsl:choose>

<xsl:call-template> and <xsl:apply-templates>

  1. <xsl:call-template>: Explicitly invokes a named template.
  2. <xsl:apply-templates>: Applies templates to child nodes that match specified rules.
Example:
  1. <xsl:template name="formatName">
  2.     <formattedName>
  3.         <xsl:value-of select="concat(lastName, ', ', firstName)"/>
  4.     </formattedName>
  5. </xsl:template>

  6. <xsl:call-template name="formatName"/>

Conditional Logic in XSLT

XSLT relies on XPath expressions to implement conditions. These are used in <xsl:if> and <xsl:when> elements. It’s important to remember that when working with string or text values, you must enclose them in apostrophes ('). However, when dealing with numeric values, apostrophes are not needed.

Basic Condition

To check a condition, you can use the <xsl:if> element. For string or text values, wrap them in apostrophes, but for numbers, no quotes are necessary.
  1. <xsl:if test="status = 'active'">
  2.     <active>true</active>
  3. </xsl:if>
In this example, the string 'active' is enclosed in apostrophes to specify that it is a text value.

Combining Conditions

You can combine multiple conditions using logical operators like and, or, and others.
  1. <xsl:if test="age &gt;= 18 and status = 'verified'">
  2.     <qualified>true</qualified>
  3. </xsl:if>
Here, both the numeric comparison (age >= 18) and the string comparison (status = 'verified') are combined. The string 'verified' is in apostrophes, but 18 is a number and does not require them.

Default Handling with <xsl:choose>

The <xsl:choose> element in XSLT allows you to evaluate multiple conditions sequentially, choosing the first condition that evaluates to true. If none of the specified conditions are met, the <xsl:otherwise> element provides a fallback, ensuring that a default value is returned.

This is particularly useful when you need to check several different conditions and have a final option if none of them apply.
  1. <xsl:choose>
  2.     <xsl:when test="age &lt; 18">
  3.         <status>minor</status>
  4.     </xsl:when>
  5.     <xsl:otherwise>
  6.         <status>adult</status>
  7.     </xsl:otherwise>
  8. </xsl:choose>
In this example:
  1. The first <xsl:when> checks if a​​​​ge is less than 18, and if true, it sets the status to 'minor'.
  2. The second <xsl:when> checks if age is between 18 and 64, setting the status to 'adult' if true.
  3. If neither condition is met, the <xsl:otherwise> block provides a fallback, setting the status to 'senior' for anyone 65 or older.
  4. Using <xsl:choose> in this way ensures that multiple conditions are checked in order, and if none match, the <xsl:otherwise> provides a default, preventing unexpected behavior.

Basics of XPath for Querying Data

XPath is an essential tool in XSLT, enabling you to navigate through the XML Data Source to select specific nodes, attributes, and values. Here are some common XPath techniques:

Simple Node Selection

XPath allows you to select specific nodes in an XML document. For instance, selecting a particular element such as a person's name is done by specifying the path to the element.
  1. <xsl:value-of select="person/name"/>
This selects the <name> node within the <person> node and outputs its value. You can apply this to any nested node structure by adjusting the XPath expression to reflect the hierarchy of elements you are targeting.

Attribute Selection

XPath makes it easy to access attributes of an element by prefixing the attribute name with @. Attributes often contain metadata or additional information about an element.
  1. <xsl:value-of select="@id"/>
Here, the XPath selects the id attribute of the current node and retrieves its value. This can be used to extract unique identifiers or any other data stored in attributes.

Conditional Queries

XPath supports conditional selection, allowing you to filter nodes based on specific criteria. You can combine conditions with predicates to select elements that meet certain conditions, such as values that exceed a threshold.
  1. <xsl:for-each select="person[age &gt;= 18]">
  2.     <adult>
  3.         <xsl:value-of select="name"/>
  4.     </adult>
  5. </xsl:for-each>
In this example, the xsl:for-each instruction iterates over all person nodes where the age is greater than or equal to 18. The name of each eligible person is then output within an <adult> element. This demonstrates how XPath can filter nodes based on dynamic conditions.

String Functions

XPath provides a variety of string functions to manipulate and query string values within nodes. These functions help refine data selection, especially when you're dealing with text-based content.

contains()Checks if a string contains a specified substring. This is useful when you want to check for the presence of a term or condition within a string.
  1. <xsl:if test="contains(description, 'urgent')">
  2.     <priority>true</priority>
  3. </xsl:if>
This condition evaluates whether the description node contains the word 'urgent'. If true, it outputs <priority>true</priority>. This can be applied to filter urgent items or highlight critical information.

starts-with(): Checks if a string starts with a specific substring. This is often used for categorizing or filtering data that follows a particular pattern.
  1. <xsl:if test="starts-with(name, 'A')">
  2.     <startsWithA>true</startsWithA>
  3. </xsl:if>
This example checks if the name starts with the letter 'A'. If true, it adds a <startsWithA>true</startsWithA> element to the output. This is particularly useful when categorizing names or values based on prefixes.

Numeric Functions

XPath also includes powerful numeric functions to perform mathematical operations or aggregate values from a set of nodes. These are essential for working with numerical data and performing calculations.

sum(): Calculates the sum of values in a node set. This function is typically used for aggregating data, such as calculating totals or averages from multiple elements.
  1. <total>
  2.     <xsl:value-of select="sum(order/price)"/>
  3. </total>
In this case, the sum() function calculates the total price from all <price> elements within an order node and outputs the result. This can be applied in scenarios where you need to calculate totals or other aggregate metrics from a list of items or transactions.

Special Characters in XSLT 1.0 with HTML Entity Alternatives

In XSLT 1.0, certain characters have special meanings within the language, and in some contexts, you need to represent these characters using their HTML entity equivalents to avoid conflicts or errors in the code. Below are some of the most common characters used in XSLT 1.0 that have HTML entity alternatives.

Common Special Characters and Their HTML Entity Codes

Greater-than sign (>)
The greater-than symbol (>) is used in XSLT for comparisons and is a reserved character in XML. When writing XSLT code, it’s often necessary to use the HTML entity &gt; to represent it.
  1. <xsl:value-of select="price &gt; 100"/>
Less-than sign (<)
Similar to the greater-than sign, the less-than symbol (<) is reserved in XML. You must use the HTML entity &lt; to represent it in contexts where it isn't part of XML syntax.
  1. <xsl:value-of select="quantity &lt; 10"/>
Ampersand (&)
The ampersand symbol (&) is used to begin an entity reference in XML and thus must be written as &amp; to avoid confusion with character references.
  1. <xsl:value-of select="name &amp; description"/>
Quotation mark (")
In XML and XSLT, double quotation marks (") are used for attribute values. To include them within the value of an attribute, you should use the entity &quot;.
  1. <xsl:value-of select="description &quot;special offer&quot;"/>
Apostrophe (')
Similar to the quotation mark, the apostrophe (') is reserved for attribute values and is represented as &apos; when needed inside an attribute.
  1. <xsl:value-of select="name &apos;John&apos;"/>
Line break
In XSLT, a line break or newline character can be represented using the HTML entity &#10;. This can be useful when you want to insert a line break in the output of the transformation or format text in a more readable way.
  1. <xsl:value-of select="'Line 1&#10;Line 2'"/>

Why Use HTML Entity Codes?

In XSLT 1.0, certain characters have specific meanings, such as < and >, which are used for defining tags. If you try to use these characters directly in your XSLT expressions or within attribute values, the XML parser may misinterpret them, leading to errors or unexpected results. By using HTML entities like &lt;, &gt;, &amp;, and others, you ensure that these characters are treated as literal text rather than XML syntax.

By understanding and using these HTML entities, you can safely include special characters in your XSLT code without causing parsing issues.

Next Steps

Now that you understand the basic building blocks of XSLT, you can start experimenting with simple transformations. Try creating an XSLT stylesheet to transform XML into a basic CSV, JSON, or hierarchical XML output. These practical examples will deepen your understanding of XSLT.

For more in-depth coverage of XSLT syntax and additional examples, be sure to read through the "Functions" article next, where we explore key XSLT functions and their applications in transformations.

    • Related Articles

    • XSLT Functions

      XSLT (Extensible Stylesheet Language Transformations) provides a wide variety of built-in functions for working with data, manipulating strings, and performing calculations. Additionally, the we've added some important functions from the EXSLT ...
    • Data Export Module - Resources List

      To help you get started and make the most of the Export Module, we offer a comprehensive set of resources. These articles cover everything from basic setup to advanced usage, ensuring that users of all experience levels can benefit from the module's ...
    • An Introduction to XSLT

      XSLT 1.0 (Extensible Stylesheet Language Transformations) is a versatile language designed for transforming XML data into various output formats, including CSV, JSON, and XML. As a core part of the W3C’s XML family of technologies, XSLT enables users ...
    • Creating a CSV Export

      Developing the export definition uses XSLT 1.0 as a processor to generate the text out. As you are developing, we encourage you to frequently preview the result to understand how your code is working. The source of the preview data is displayed in ...
    • Creating a JSON Export

      Developing the export definition uses XSLT 1.0 as a processor to generate the text out. As you are developing, we encourage you to frequently preview the result to understand how your code is working. The source of the preview data is displayed in ...