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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…