xslt实现递归

http://jonmifsud.com/blog/xslt-recursion/

 

Where would XSLT Recursion be useful

There are plenty of times where XSLT Recursion can really make your life simple, I'll take a simple use-case. Below find some XML have a look at it.

              <root>
    <navigation>
        <page id='1'>Home</page>
        <page id='2'>About</page>
        <page id='3' parent='2'>Staff</page>
        <page id='4'>Contact</page>
        <page id='5'>Terms & Conditions</page>
        <page id='6' parent='3'>John Doe</page>
        <page id='7' parent='3'>Directors</page>
    </navigation>
</root>

            

So there you have an XML representing some pages from a web-page, which has hierarchical properties described in the parent attribute. The system does not define a limit of sub-pages allowed so it is safe to assume that there could be more then three levels. What would you do if you had to transform this to basic breadcrumbs using XSLT without Recursion? Most likely do a three level-check to add the next level. Lets see how a Recursive XSLT template would look like.

              <xsl:template name='breadcrumb'>
    <xsl:with-param name='pageid'>
    <!-- Define a variable to select the current page -->
    <xsl:variable name='currentPage' select='/root/navigation/page[@id=$pageid]'/>
    <xsl:if test='$currentPage/@parent'
        <!-- If this page has a parent do a recursive call using the parent id -->
        <xsl:call-template name='breadcrumb'>
            <xsl:with-param name='pageid' select='$currentPage/@parent'>
        </xsl:call-template>
        <xsl:text> / </xsl:text>
    </xsl:if>
    <xsl:value-of select='$currentPage'>
</xsl:template>

            

The above XSLT Recursion example explains how to transform the XML into a breadcrumb output for the current page. Note that in real breadcrumbs you would also have links which were omitted for the simplicity of the example

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值