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

[url]http://tech.sina.com.cn/s/s/2008-06-18/1202698101.shtml[/url]
通过XSL template与import实现代码重用
http://www.sina.com.cn 2008年06月18日 12:02 IT168.com

【IT168技术文档】

在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 >
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值