Advanced XSLT: Conditions, Sorting, and Modular Design

Unit 4â€ĸCLO04, CLO05

Learning Objectives

Course Learning Outcomes

CLO04
CLO05

Course Outcomes

CO04
CO05
â„šī¸

Introduction

Real-world transforms branch, classify, and reuse logic. Conditions, variables, and separate templates keep stylesheets maintainable. You also learn to compute values (totals, averages) and to modularize code.

Study tracker

Mark what you have completed for this topic.

0% done

The Basics

Control and reuse

  • xsl:if for single checks; xsl:choose for multi-branch logic.
  • Variables hold computed values or XPath results (immutable once set).
  • Named templates enable reuse across documents.
  • Import/include split large stylesheets for teams.

Technical Details

Snippets worth memorizing

Branching

<xsl:choose>
  <xsl:when test="price &gt; 500">Expensive</xsl:when>
  <xsl:otherwise>Affordable</xsl:otherwise>
</xsl:choose>

Variables and totals

<xsl:variable name="total" select="sum(/library/book/price)"/>
<p>Total: <xsl:value-of select="$total"/></p>

Modularity

<xsl:call-template name="renderRow"/>

Examples

Classification example

<xsl:template match="book">
  <tr>
    <td><xsl:value-of select="title"/></td>
    <td>
      <xsl:choose>
        <xsl:when test="number(price) &gt; 500">High</xsl:when>
        <xsl:otherwise>Low</xsl:otherwise>
      </xsl:choose>
    </td>
  </tr>
</xsl:template>

Sorting with numbers

<xsl:for-each select="library/book">
  <xsl:sort select="number(price)" data-type="number" order="ascending"/>
  <xsl:value-of select="title"/>
</xsl:for-each>

Self-check

Real-World Use

Apply it

  • Add a price band label using xsl:choose.
  • Compute a grand total and average with sum() and count().
  • Move row rendering into a named template and call it, keeping the root template slim.

📝 For exams

Likely questions

  • Contrast xsl:if with xsl:choose.
  • How does xsl:sort treat numbers vs strings?
  • Two advantages of named templates or imports.

✨ Key points

Takeaways

  • Conditions make transforms context-aware.
  • Variables simplify repeated calculations.
  • Modular stylesheets stay maintainable as projects grow.