The <xsl:for-each> element allows you to do looping in XSLT.
<xsl:for-each>ÔªËØÔÊÐíÔÚXSLTÀïʹÓÃÑ»·Óï¾ä¡£
The <xsl:for-each> Element
<sxl:-each>ÔªËØ
The XSL <xsl:for-each> element can be used to select every XML element of a specified node-set:
XSL<xsl:for-each>ÔªËØµÄ×÷ÓÃÊÇ£ºÑ¡ÔñÈκÎÒ»¸ö¾ßÓÐÖ¸¶¨µÄ½ÚµãÉèÖã¨node-set£©µÄXMLÔªËØ¡£
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:template match="/"> |
Note: The value of the select attribute is an XPath expression. An XPath expression works like navigating a file system; where a forward slash (/) selects subdirectories.
×¢Òâ: Ñ¡Ôñ£¨select£©ÊôÐÔÖµÊÇÒ»¸öXPathµÄ±í´ïʽֵ¡£XPath±í´ïʽÖ÷ÒªÓÃÓÚÀàËÆÎļþϵͳµÄ²Ù×÷£¬¶øÕâ¸öÎļþϵͳÀïÊÇͨ¹ýÔÚǰ¶ËÌí¼Ó“/”Ñ¡Ôñ×ÓĿ¼¡£
The result of the transformation above will look like this:
ÉÏÃæ×ª»»½á¹ûÈçÏ£º
My CD Collection
ÎÒµÄCD¼¯
| Title | Artist |
|---|---|
| Empire Burlesque | Bob Dylan |
| Hide your heart | Bonnie Tyler |
| Greatest Hits | Dolly Parton |
| Still got the blues | Gary More |
| Eros | Eros Ramazzotti |
| One night only | Bee Gees |
| Sylvias Mother | Dr.Hook |
| Maggie May | Rod Stewart |
| Romanza | Andrea Bocelli |
| When a man loves a woman | Percy Sledge |
| Black angel | Savage Rose |
| 1999 Grammy Nominees | Many |
| For the good times | Kenny Rogers |
| Big Willie style | Will Smith |
| Tupelo Honey | Van Morrison |
| Soulsville | Jorn Hoel |
| The very best of | Cat Stevens |
| Stop | Sam Brown |
| Bridge of Spies | T`Pau |
| Private Dancer | Tina Turner |
| Midt om natten | Kim Larsen |
| Pavarotti Gala Concert | Luciano Pavarotti |
| The dock of the bay | Otis Redding |
| Picture book | Simply Red |
| Red | The Communards |
| Unchain my heart | Joe Cocker |
View the XML file, View the XSL file, and View the result
XML Îļþ, XSL Îļþ, ÒÔ¼° ½á¹û
Filtering the Output
¹ýÂ˽á¹û£¨Filtering the Output£©
We can also filter the output from the XML file by adding a criterion to the select attribute in the <xsl:for-each> element.
ÎÒÃÇÒ²¿ÉÒÔ´ÓXMLÎļþͨ¹ý½«Ò»¸ö¹æÔòÌí¼Óµ½<xsl:for-each>ÔªËØÖеÄÑ¡ÔñÊôÐÔÀ´¹ýÂ˽á¹û¡£
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
Legal filter operators are:
Õý¹æµÄ¹ýÂ˲Ù×÷ÊÇ£º
- = (equal)
= (µÈÓÚ) - != (not equal)
!= (²»µÈÓÚ) - < less than
< СÓÚ - > greater than
> ´óÓÚ
Take a look at the adjusted XSL style sheet:
ÈÃÎÒÃÇÀ´¿´Ò»Ïµ÷Õû¹ýµÄXSLÑùʽ±í£º
<?xml version="1.0" encoding="ISO-8859-1"?> <xsl:template match="/"> |
The result of the transformation above will look like this:
ÉÏÃæµÄת»»½á¹ûÈçÏ£º
My CD Collection
ÎÒµÄCD¼¯
| Title | Artist |
|---|---|
| Empire Burlesque | Bob Dylan |
View the XML file, View the XSL file, View the result
XMLÎļþ, XSLÎļþ, ½á¹û