技术开发 频道

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


【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 >
0
相关文章