XSLT When Tutorial šŸŽÆ

beginner
17 min

XSLT When Tutorial šŸŽÆ

Welcome to our XSLT When tutorial! In this comprehensive guide, we'll explore the XSLT when statement, a powerful tool for conditional processing in XML documents. Let's get started! šŸ“

Understanding XSLT when šŸ’”

The XSLT when statement is used within xsl:choose for conditional logic in XSLT templates. It checks if a condition is true, and if so, executes the corresponding template or output a result.

xml
<xsl:choose> <xsl:when test="condition"> <!-- Code to execute when condition is true --> </xsl:when> <!-- More when statements and an optional xsl:otherwise --> </xsl:choose>

šŸ“ Note: Replace condition with your own condition using XPath expressions.

A Practical Example šŸ’”

Let's consider an XML document containing student information:

xml
<students> <student id="1"> <name>John Doe</name> <age>23</age> <gender>Male</gender> </student> <student id="2"> <name>Jane Smith</name> <age>22</age> <gender>Female</gender> </student> </students>

Using XSLT, we can create a transformation to filter students based on their age:

xml
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body> <h2>Students older than 20:</h2> <xsl:apply-templates select="//student[age > 20]"/> </body> </html> </xsl:template> <xsl:template match="student"> <ul> <li>ID: <xsl:value-of select="@id"/></li> <li>Name: <xsl:value-of select="name"/></li> <li>Age: <xsl:value-of select="age"/></li> <li>Gender: <xsl:value-of select="gender"/></li> </ul> </xsl:template> </xsl:stylesheet>

In this example, we use XSLT to filter students based on their age (age > 20).

Quiz Time šŸ’”

Quick Quiz
Question 1 of 1

What does the XSLT `when` statement do in an XSLT transformation?

Wrapping Up šŸ’”

We've covered the basics of XSLT when in this tutorial. Now that you understand how to use XSLT for conditional processing, you're ready to apply these concepts to your own XML documents and create powerful transformations. Happy coding! šŸŽ‰

šŸ’” Pro Tip: Don't forget to explore the xsl:choose statement and the xsl:otherwise template for handling multiple conditions.

šŸ“ Note: For more advanced XSLT examples and tutorials, be sure to visit CodeYourCraft regularly!


šŸ’” Pro Tip: To learn more about XPath, the expression language used in XSLT, check out our XPath tutorial!