Condition judgment and sorting

1. <xsl:sort> Sorting

Used together with <xsl:for-each> to sort data inside the loop.

Syntax Rules
  1. Mandatory placement: Place it inside <xsl:for-each> and before any output content.
  2. select="field_name": Specify which node to sort by.
  3. Ascending order is the default; add order="descending" for descending sort.

Example: sort students by age in ascending order

<xsl:for-each select="class/student">
    <xsl:sort select="age"/>
    <li><xsl:value-of select="name"/><xsl:value-of select="age"/></li>
</xsl:for-each>Code language: HTML, XML (xml)

Descending example:

<xsl:sort select="age" order="descending"/>Code language: HTML, XML (xml)

2. <xsl:if> Single‑condition judgment

Output content only when condition matches. No else branch available.

<xsl:if test="condition_expression">
    Content shown when condition is satisfied
</xsl:if>Code language: HTML, XML (xml)

Important: Inside the test attribute, greater‑than > must be written as &gt;, less‑than < as &lt;

Example: filter students taller than 160

<xsl:for-each select="class/student">
    <xsl:sort select="age"/>
    <xsl:if test="height &gt; 160">
        <li><xsl:value-of select="name"/><xsl:value-of select="age"/></li>
    </xsl:if>
</xsl:for-each>Code language: HTML, XML (xml)

Condition judgment and sorting

Previous:

Leave a Reply

Your email address will not be published. Required fields are marked *