Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

creating a tree structure from a delimited string xslt 2.0

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...