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! š
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.
<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.
Let's consider an XML document containing student information:
<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:
<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).
What does the XSLT `when` statement do in an XSLT transformation?
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!