通过XSL template与import实现代码重用

在OO的世界里,代码复用是很重要的思想之一.在DotNet下,代码复用的一个典型就是企业库了,把很多常用的代码都封装成一个库了.在XSL里也可以借用这种思想,利用template与import实现代码实现XSL的重用,如果使用XSL开发过很多XML相关应用,肯定会有很多代码可能是经常能用到的,把它封装到一个文件下,比如:
 1 <? xml version="1.0" ?>
 2 < xsl:stylesheet  version ="1.0"  xmlns:xsl ="http://www.w3.org/1999/XSL/Transform" >
 3     <!--
 4      模板名称:replacing-substring。
 5
     模板作用:替换指定文本的特定字符。
 6
     参数列表:text表示要处理的文本;from表示要替换的目标字符;to表示替换的结果字符。
 7     -->

 8     < xsl:template  name ="replacing-substring" >
 9        < xsl:param  name ="text"   />
10        < xsl:param  name ="from"   />
11        < xsl:param  name ="to"   />
12        < xsl:choose >
13          < xsl:when  test ="contains($text,$from)" >
14             < xsl:value-of  select ="substring-before($text,$from)"   />
15             < xsl:copy-of  select ="$to"   />
16             < xsl:call-template  name ="replacing-substring" >
17                < xsl:with-param  name ="text"  select ="substring-after($text,$from)"   />
18                < xsl:with-param  name ="from"  select ="$from"   />
19                < xsl:with-param  name ="to"  select ="$to"   />
20             </ xsl:call-template >
21          </ xsl:when >
22          < xsl:otherwise >
23             < xsl:copy-of  select ="$text"   />
24          </ xsl:otherwise >
25        </ xsl:choose >
26     </ xsl:template >
27 </ xsl:stylesheet >
这里只写出了一个方法,以后有更多的方法可以加入到这个文件中,我把它命名为Common.xslt
在需要的地方import进来:
 1 <? xml version="1.0" ?>
 2 < xsl:stylesheet  version ="1.0"  xmlns:xsl ="http://www.w3.org/1999/XSL/Transform" >
 3     < xsl:import  href ="Common.Xslt"   />
 4     < xsl:template  match ="stories" >
 5        < table >
 6           < td >
 7           < xsl:call-template  name ="replacing-substring" >
 8              < xsl:with-param  name ="text"  select ="story[1]/text()"   />
 9              < xsl:with-param  name ="from" > | </ xsl:with-param >
10              < xsl:with-param  name ="to" >< br  /></ xsl:with-param >
11           </ xsl:call-template >
12           </ td >
13        </ table >
14     </ xsl:template >
15 </ xsl:stylesheet >
作用就是把story的文本值里的|符号替换成<br />,我把这个文件命名为:project.xslt
使用这个xsl文件的示例XML文件如下:
 1 <? xml version="1.0" ?>
 2 <? xml-stylesheet type="text/xsl" href="project.xslt" ?>
 3 < stories >
 4      < story >
 5   1,从前有一条村|村里有一户人家|家里有个小孩子.
 6      </ story >

 7      < story >
 8           2,从前有一条村|村里有一户人家|家里有个小孩子.
 9          </ story >

10 </ stories >
11
在IE里显示的效果如下:
1,从前有一条村
村里有一户人家
家里有个小孩子

参考:
C# XML入门经典 清华大学出版社
XSLT精要 清华大学出版社


注意:以上的XML代码的<后面,以及>前面都是没有空格,文章里显示的空格是FTB Editor的问题
posted @ 2006-03-28 00:50  kwklover  阅读(1951)  评论(0编辑  收藏  举报