当前位置: 首页 > 教程 > XSLT >

XSLT <for-each>标签

精华
小牛编辑
97浏览
2023-03-14

<xsl:for-each>标记为每个节点重复应用模板。

声明
以下是<xsl:for-each>元素的语法声明

<xsl:for-each
   select = Expression >  
</xsl:for-each>

属性

  • Select - 要在当前上下文中计算的XPath表达式,以确定要迭代的节点集。

元素

  • 父元素 - xsl:attribute, xsl:comment, xsl:copy, xsl:element, xsl:fallback, xsl:foreach, xsl:if, xsl:message, xsl:otherwise, xsl:param, xsl:processing-instruction, xsl:template, xsl:variable, xsl:when, xsl:with-param, 输出元素.
  • 子元素 - xsl:apply-imports, xsl:apply-templates, xsl:attribute, xsl:call-template, xsl:choose, xsl:comment, xsl:copy, xsl:copy-of, xsl:element, xsl:fallback, xsl:for-each, xsl:if, xsl:message, xsl:number, xsl:processing-instruction, xsl:sort, xsl:text, xsl:value-of, xsl:variable等。

示例

此示例通过迭代每个学生创建一个<student>元素的表格,其中包含其属性rollno及其子素:<firstname><lastname><nickname><marks>

文件:students.xml -

<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href = "students.xsl"?> 
<class> 
   <student rollno = "10010">
      <firstname>Machine</firstname> 
      <lastname>Lee</lastname> 
      <nickname>Machine</nickname> 
      <marks>85</marks>
   </student> 
   <student rollno = "10020"> 
      <firstname>Max</firstname> 
      <lastname>Su</lastname> 
      <nickname>Maxsu</nickname> 
      <marks>95</marks>
   </student> 
   <student rollno = "10030"> 
      <firstname>Yii</firstname> 
      <lastname>Bai</lastname> 
      <nickname>Yiibai</nickname> 
      <marks>90</marks> 
   </student> 
</class>

文件:students.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>学生信息列表</h2> 
            <table border = "1"> 
               <tr bgcolor = "#3498db"> 
                  <th>Roll No</th> 
                  <th>First Name</th> 
                  <th>Last Name</th> 
                  <th>Nick Name</th> 
                  <th>Marks</th> 
               </tr> 

               <xsl:for-each select = "class/student"> 

                  <tr> 
                     <td><xsl:value-of select = "@rollno"/></td> 
                     <td><xsl:value-of select = "firstname"/></td> 
                     <td><xsl:value-of select = "lastname"/></td> 
                     <td><xsl:value-of select = "nickname"/></td> 
                     <td><xsl:value-of select = "marks"/></td> 
                  </tr> 
               </xsl:for-each> 

            </table> 
         </body> 
      </html> 
   </xsl:template>  
</xsl:stylesheet>

在浏览器中打上面文件:student.xml,效果如下所示 -