XSLT <apply-template>標籤


<xsl:apply-template>標記用信號通知XSLT處理器根據每個所選節點的型別和上下文查詢要應用的相應模板。

宣告

以下是<xsl:apply-template>元素的語法宣告。

<xsl:apply-template 
   select = Expression 
   mode = QName > 
</xsl:apply-template>

屬性

  • select - 用於處理由XPath表示式選擇的節點,而不是處理所有子節點。
  • mode - 允許多次處理由其限定名稱指定的元素,每次生成不同的結果。

元素

  • 父元素 - 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:sort, xsl:with-param

範例

此範例通過疊代每個學生建立一個<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> 
            <xsl:apply-templates select = "class/student" /> 
         </body> 
      </html> 
   </xsl:template>  

   <xsl:template match = "class/student"> 
      <xsl:apply-templates select = "@rollno" /> 
      <xsl:apply-templates select = "firstname" /> 
      <xsl:apply-templates select = "lastname" /> 
      <xsl:apply-templates select = "nickname" /> 
      <xsl:apply-templates select = "marks" /> 
      <br /> 
   </xsl:template>  

   <xsl:template match = "@rollno"> 
      <span style = "font-size = 22px;"> 
         <xsl:value-of select = "." /> 
      </span> 
      <br /> 
   </xsl:template>  

   <xsl:template match = "firstname"> 
      First Name:<span style = "color:blue;"> 
         <xsl:value-of select = "." /> 
      </span> 
      <br /> 
   </xsl:template>  

   <xsl:template match = "lastname"> 
      Last Name:<span style = "color:green;"> 
         <xsl:value-of select = "." /> 
      </span> 
      <br /> 
   </xsl:template>  

   <xsl:template match = "nickname"> 
      Nick Name:<span style = "color:red;"> 
         <xsl:value-of select = "." /> 
      </span> 
      <br /> 
   </xsl:template>  

   <xsl:template match = "marks"> 
      Marks:<span style = "color:gray;"> 
         <xsl:value-of select = "." /> 
      </span> 
      <br /> 
   </xsl:template>  

</xsl:stylesheet>

在瀏覽器中打上面檔案:student.xml,效果如下所示 -