XSLT <xsl:for-each> 元素


<xsl:for-each> 元素允許您在 XSLT 中進行迴圈。


<xsl:for-each> 元素

XSL <xsl:for-each> 元素可用於選取指定的節點集中的每個 XML 元素:

實例

<?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>

注意:select 屬性的值是一個 XPath 運算式。這個 XPath 運算式的工作方式類似於定位某個檔系統,在其中正斜杠(/)可選擇子目錄。


過濾輸出結果

通過在 <xsl:for-each> 元素中添加一個選擇屬性的判別式,我們也可以過濾從 XML 檔輸出的結果。

<xsl:for-each select="catalog/cd[artist='Bob Dylan']">

合法的過濾運算符:

  • = (等於)
  • != (不等於)
  • &lt; (小於)
  • &gt; (大於)

看看調整後的 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> <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>