creating a tree structure from a delimited string xslt 2.0

寵の児 提交于 2019-12-14 03:36:23

问题


I have a input string looks like below

test1->test2->test3

I want to build a tree structure like the below.

-test1 +test2

How can I convert the string to tree structure using xslt 2.0.


回答1:


The following stylesheet splits the string into a sequence of strings using tokenize() and then recursively calls the "nest" template to create an element for the first item in the sequence and then call the template with the remaining strings to generate the nested elements.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
    <xsl:output indent="yes"/>

    <xsl:template match="/">
        <xsl:variable name="delimited-input" select="'test1->test2->test3'"/>
        <xsl:call-template name="nest">
            <xsl:with-param name="names" select="tokenize($delimited-input, '->')"/>
        </xsl:call-template>
     </xsl:template>

    <xsl:template name="nest" as="element()*">
        <xsl:param name="names" as="xs:string*"/>
        <xsl:if test="exists($names)">
            <xsl:variable name="head" select="$names[position() = 1]"/>
            <xsl:element name="{$head}">
                <xsl:call-template name="nest">
                    <xsl:with-param name="names" select="$names[position() > 1]"/>
                </xsl:call-template>
            </xsl:element>
        </xsl:if>
    </xsl:template>

</xsl:stylesheet>

Produces the following nested element structure:

<test1>
   <test2>
      <test3/>
   </test2>
</test1>

Assuming that you want to produce HTML, adjust to generate <div> or whatever specific elements necessary.



来源:https://stackoverflow.com/questions/34840940/creating-a-tree-structure-from-a-delimited-string-xslt-2-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!