XML
Beginner
1 min read
XSLT Control Structures and Variables
Example
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8"/>
<!-- Stylesheet-level parameter (passed by caller) -->
<xsl:param name="maxPrice" select="50"/>
<xsl:template match="/">
<!-- Variable: count of all books -->
<xsl:variable name="bookCount" select="count(//book)"/>
<xsl:text>Total books: </xsl:text>
<xsl:value-of select="$bookCount"/>
<xsl:text> </xsl:text>
<!-- for-each with sort -->
<xsl:for-each select="//book">
<xsl:sort select="year" data-type="number" order="descending"/>
<!-- if: only list affordable books -->
<xsl:if test="price <= $maxPrice">
<xsl:value-of select="year"/>
<xsl:text> — </xsl:text>
<xsl:value-of select="title"/>
<xsl:text> ($</xsl:text>
<xsl:value-of select="price"/>
<xsl:text>) </xsl:text>
</xsl:if>
</xsl:for-each>
<!-- choose / when / otherwise -->
<xsl:variable name="total" select="sum(//price)"/>
<xsl:text>Budget status: </xsl:text>
<xsl:choose>
<xsl:when test="$total < 20">Low spend</xsl:when>
<xsl:when test="$total < 60">Moderate spend</xsl:when>
<xsl:otherwise>High spend</xsl:otherwise>
</xsl:choose>
<xsl:text> </xsl:text>
<!-- Named template call -->
<xsl:call-template name="separator"/>
</xsl:template>
<!-- Named template: reusable output fragment -->
<xsl:template name="separator">
<xsl:text>---------------------------- </xsl:text>
</xsl:template>
</xsl:stylesheet>