XSLT元素----xsl:template

一 xsl:template (template一般翻译为模板)

它的作用就是为特定的结点定义可重复使用的模板。跟函数的作用有点相似,你可以在一处定义,多次调用,在XSLT里,调用模板的方法有xsl:call-template和xsl:apply-templates。而且在定义模板的时候还可以指定不同的mode值来重载这个template,当然,你在调用的时候也要指定mode。

格式:<xsl:template match="*" mode="A" name="">
match属性指定匹配的结点类型,比如“*”是匹配任意类型的结点。
mode属性用来区分匹配同个结点的模板。
name属性不是必须的。w如果你是通过xsl:call-template来调用这个模板的话,必须指定这个属性。关于xsl:call-template和xsl:apply-templates的区别,可以查GOOGLE。

备注:
在 XPath 中,有七种类型的节点:元素、属性、文本、命名空间、处理指令、注释以及文档(根)节点,具体看w3cschool教程。

二 例子

data.xml

<?xml-stylesheet type="text/xsl" href="sample.xslt"?>
<catalog>
 <book id="bk101">
  <author>Gambardella, Matthew</author>
  <title>XML Developer's Guide</title>
  <genre>Computer</genre>
  <price>44.95</price>
  <publish_date>2000-10-01</publish_date>  
  <description>An in-depth look at creating applications with XML.</description>
 </book>
 <book id="bk102">
  <author>Ralls, Kim</author>
  <title>Midnight Rain</title>
  <genre>Fantasy</genre>
  <price>5.95</price>
  <publish_date>2000-12-16</publish_date>
  <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description>
 </book>
 <book id="bk111">
  <author>O'Brien, Tim</author>
  <title>MSXML3: A Comprehensive Guide</title>
  <genre>Computer</genre>
  <price>36.95</price>
  <publish_date>2000-12-01</publish_date>
  <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more.</description>
 </book>
</catalog>

sample.xslt

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
 <xsl:output method="html"/>
 <xsl:template match="/">
  <html>
   <body>
    <xsl:apply-templates/>
   </body>
  </html>
 </xsl:template>
 <xsl:template match="*">
   node name is: <b>
   <xsl:value-of select="name()"/>
  </b>
  <br/>
  <xsl:apply-templates/>
  <br/>
 </xsl:template>
</xsl:stylesheet>

三 代码说明

在这之前,请了解一下XSLT的工作原理,查GOOGLE 

<xsl:template match="/">
匹配XML文档的根节点,它相当于C里的Main函数,就算你不写这个TEMPLATE,XSLT处理器也会内建一个与此类似的模板,不信的话,可以将该模板删除,再调试看看。关于内建模板,必须要掌握,有助于深入的理解XSLT。

 <xsl:apply-templates/>
它的作用是告诉XSLT处理器去查找当前上下文的孩子节点,然后实例化相应的TEMPLATE来处理这些孩子节点。有点FOR循环的意思,如果去掉这行,XSLT处理器就不再往下遍历孩子节点了。

关健是以上这两部分,其他都好理解。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值