Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...