Loop

Core Tags

1. <xsl:value-of>

Purpose: Extract text content from the specified XML node and output it to the result document.

<!-- Directly fetch the title value under the first catalog/cd (only gets first entry without loop) -->
<xsl:value-of select="catalog/cd/title" />Code language: HTML, XML (xml)

When used without the <xsl:for-each> loop, only the first matching node will be retrieved, and full‑data iteration is unavailable.

2. <xsl:for-each>

Purpose: Iterate over a set of matched XML nodes to process multiple records in batches.

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

XPath Filter Syntax

Append [condition] after the select path to filter nodes and implement data filtering.

<!-- Output only cd records where artist equals Bob Dylan -->
<xsl:for-each select="catalog/cd[artist='Bob Tom']">Code language: HTML, XML (xml)

Supported Operators

OperatorXPath SyntaxMeaning
==Equal to
!=!=Not equal to
<&lt;Less than (do not write < directly; escaping is mandatory)
>&gt;Greater than (do not write > directly; escaping is mandatory)

Example: filter CDs with price less than 10

<xsl:for-each select="catalog/cd[price &lt; 10]">Code language: HTML, XML (xml)

Previous Example

student.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
</head>
<body>
    <ul>
        <!-- Iterate all student nodes -->
        <xsl:for-each select="class/student">
            <li><xsl:value-of select="name"/><xsl:value-of select="age"/></li>
        </xsl:for-each>
    </ul>
</body>
</html>
</xsl:template>
</xsl:stylesheet>Code language: HTML, XML (xml)

Associated XML (student.xml)

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="student.xsl"?>
<class>
    <student>
        <name>Jack</name>
        <age>16</age>
    </student>
    <student>
        <name>Jim</name>
        <age>12</age>
    </student>
</class>Code language: HTML, XML (xml)

Add Filtering

Only output students older than 14

<xsl:for-each select="class/student[age &gt; 14]">
    <li><xsl:value-of select="name"/><xsl:value-of select="age"/></li>
</xsl:for-each>Code language: HTML, XML (xml)

Loop

Leave a Reply

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