从定界字符串 xslt 2.0 创建树结构 [英] creating a tree structure from a delimited string xslt 2.0

查看:46
本文介绍了从定界字符串 xslt 2.0 创建树结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的输入字符串

test1->test2->test3

我想构建一个如下所示的树结构.

-test1+测试2

如何使用 xslt 2.0 将字符串转换为树结构.

解决方案

以下样式表使用 tokenize() 将字符串拆分为一系列字符串,然后递归调用嵌套"模板创建序列中第一项的元素,然后使用剩余的字符串调用模板以生成嵌套元素.

<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:模板><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:模板></xsl:stylesheet>

产生以下嵌套元素结构:

<测试2><test3/></test2></test1>

假设您要生成 HTML,请调整以生成

或任何必要的特定元素.

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.

解决方案

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.

这篇关于从定界字符串 xslt 2.0 创建树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆