XSLT Variable Tutorial 🎯

beginner
7 min

XSLT Variable Tutorial 🎯

Welcome to our XSLT Variable tutorial! In this lesson, we'll dive into one of the most powerful features of XSLT (Extensible Stylesheet Language Transformations) - Variables. 📝

What are XSLT Variables?

Variables in XSLT are storage areas that hold values for later use during the transformation process. They can be used to store temporary results, repeat certain elements, or perform calculations. 💡 Pro Tip: Variables are declared using the xsl:variable element.

Declaring a Simple Variable 💡

Let's start with a simple example. We'll create a variable called total and store the sum of two numbers:

xml
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:variable name="number1" select="10"/> <xsl:variable name="number2" select="20"/> <xsl:variable name="total"> <xsl:sum select="$number1 + $number2"/> </xsl:variable> <xsl:template match="/"> <html> <body> <h1>Total: <xsl:value-of select="$total"/></h1> </body> </html> </xsl:template> </xsl:stylesheet>

In the example above, we declare two variables number1 and number2 and assign them values 10 and 20, respectively. Then, we declare a variable total and assign the result of the sum of number1 and number2. Finally, we output the total as an HTML document.

Using Variables in XSLT Templates 💡

Variables can be used in XSLT templates to simplify complex transformations. Here's an example where we create a template that calculates the factorial of a given number:

xml
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template name="factorial"> <xsl:param name="n"/> <xsl:if test="$n &lt;= 1"> <xsl:value-of select="$n"/> </xsl:if> <xsl:value-of select="$n * (factorial($n - 1))"/> </xsl:template> <xsl:variable name="number" select="5"/> <xsl:variable name="factorialResult"> <xsl:call-template name="factorial"> <xsl:with-param name="n" select="$number"/> </xsl:call-template> </xsl:variable> <xsl:template match="/"> <html> <body> <h1>Factorial of {xsl:value-of select="$number"} is {xsl:value-of select="$factorialResult"}</h1> </body> </html> </xsl:template> </xsl:stylesheet>

In this example, we define a reusable template factorial that takes a parameter n and calculates its factorial. We then declare a variable number with a value of 5 and call the factorial template to get the factorial result, which we store in the variable factorialResult. Finally, we output the factorial result in an HTML document.

Quiz 💡

Quick Quiz
Question 1 of 1

Which XSLT element is used to declare a variable?

Keep learning, and happy coding! 💡 Pro Tip: Check out our other XSLT tutorials for more in-depth explanations and examples. 🎯