xsl递增变量解决家族树的问题

xml没有递增变量的标准方法一旦定义了一个变量,他就不能改变
这相当于java中的final字段不过在一些情况中结合模板的递归方法可以实现类

似的结果
假如xml文件为familyTree.xml

 1<person name="Otto">
 2<person name="Sandra">
 3<person name="Lichao">
 4<person name="Zhangsan"></person>
 5</person>
 6<person name="Eric">
 7<person name="HaLi"></person>
 8</person>
 9<person name="Lisi">
10<person name="HeLi"></person>
11<person name="Andy"></person>
12</person>
13</person>
14</person>

这段xml中每个

 1<person>元素可以包含任意个数的<person>子元素   
 2这就叫家族数,在显示这个家族树的时候应根据家族系来缩进文本是个恰当的 
 3
 4做法这就给人们之间关系给一个可视化的表示   
 5例如   
 6Otto   
 7Sandra   
 8Lichao   
 9Zhangsan   
10Eric   
11HaLi   
12Lisi   
13HeLi   
14Andy   
15这样就得用递归的方法写xslt样式表   
16familyTree.xslt   
17<?xml version="1.0" encoding="UTF-8"?>
18<xsl:stylesheet version="1.0" xmlns:xsl=" http://www.w3.org/1999/XSL/Transform ">
19<xsl:output method="html"></xsl:output>
20<xsl:template match="/">
21<html>
22<body>
23<!-- select the top level person -->
24<xsl:apply-templates select="person">
25<xsl:with-param name="level" select="'0'"></xsl:with-param>
26</xsl:apply-templates>
27</body>
28</html>
29</xsl:template>
30<!-- Output information for a person and recursively select   
31all children. -->
32<xsl:template match="person">
33<xsl:param name="level"></xsl:param>
34<!-- indent according to the level -->
35<div style="text-indent:{$level}em">
36<xsl:value-of select="@name"></xsl:value-of>
37</div>
38<!-- recursively select children, incrementing the 
39
40level -->
41<xsl:apply-templates select="person">
42<xsl:with-param name="level" select="$level + 
43
441"></xsl:with-param>
45</xsl:apply-templates>
46</xsl:template>
47</xsl:stylesheet>
48
49和通常一样这个样式表以匹配文本的根节点作为开始,并输入一个基本的 
50
51html文档,然后它选择<person>根元素将level=0作为参数传递到匹配person的 
52
53模板:<xsl:apply-templates select="person">
54<xsl:with-param name="level" select="'0'"></xsl:with-param>
55</xsl:apply-templates>   
56而person模板使用一个html的div在一个新行上显示每个人的名字并以em为单位 
57
58设定文本的缩进。最后递归的调用person模板,将$level+1作为参数传递,尽 
59
60管这样并不会递增一个已有的变量但是他的确传递了一个新的局部变量到模板 
61
62中。该变量的值大于以前的值,与递归的处理的技巧不同,实际上在xslt中并 
63
64没有递增变量值的方法</person></person></person>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus