Elemento XSLT <xsl:for-each>
L'elemento <xsl:for-each> consente di eseguire cicli in XSLT.
L'elemento <xsl:for-each>
L'elemento XSL <xsl:for-each> può essere utilizzato per selezionare ogni elemento XML di un set di nodi specificato:
Esempio
<?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>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Nota: il valore dell'attributo select è un'espressione XPath. Un'espressione XPath funziona come la navigazione in un file system; dove una barra (/) seleziona le sottodirectory.
Filtraggio dell'output
Possiamo anche filtrare l'output dal file XML aggiungendo un criterio all'attributo select nell'elemento <xsl:for-each>.
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
Gli operatori di filtri legali sono:
- = (uguale)
- != (non uguale)
- < meno di
- > più grande di
Dai un'occhiata al foglio di stile XSL modificato:
Esempio
<?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>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>