如何将具有定义级别的元素序列放入元素结构中? [英] How can i get a sequence of elements with a defined level into an element structure?

查看:21
本文介绍了如何将具有定义级别的元素序列放入元素结构中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用 xslt 模板来实现:

How ca i use an xslt template to get from this:

<attribute name="Foo" level="1"/>
<attribute name="Bar" level="2"/>
<attribute name="Lorem" level="2"/>
<attribute name="Ipsum" level="3"/>

这样的结构:

<attribute name="Foo">
    <attribute name="Bar"/>
    <attribute name="Lorem">
        <attribute name="Ipsum"/>
    </attribute>
</attribute>

我可以使用 XSLT 和 XPATH 2.0,我尝试了不同的分组方法,但我不知道如何递归.

I can use XSLT and XPATH 2.0 and i tried different things with grouping but i don't know how to get a recursion into it.

推荐答案

如果你使用一个应用 for-each-group group-starting-with 你得到的函数

If you use a function applying a for-each-group group-starting-with you get

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="xs mf">

    <xsl:output indent="yes"/>

    <xsl:function name="mf:group" as="element(attribute)*">
        <xsl:param name="attributes" as="element(attribute)*"/>
        <xsl:param name="level" as="xs:integer"/>
        <xsl:for-each-group select="$attributes" group-starting-with="attribute[@level = $level]">
            <attribute name="{@name}">
                <xsl:sequence select="mf:group(current-group() except ., $level + 1)"/>
            </attribute>
        </xsl:for-each-group>
    </xsl:function>

    <xsl:template match="root">
        <xsl:sequence select="mf:group(attribute, 1)"/>
    </xsl:template>

</xsl:transform>

转换

<root>
    <attribute name="Foo" level="1"/>
    <attribute name="Bar" level="2"/>
    <attribute name="whatever" level="3"/>
    <attribute name="Lorem" level="2"/>
    <attribute name="Ipsum" level="3"/>
    <attribute name="foobar" level="3"/>
</root>

进入

<attribute name="Foo">
   <attribute name="Bar">
      <attribute name="whatever"/>
   </attribute>
   <attribute name="Lorem">
      <attribute name="Ipsum"/>
      <attribute name="foobar"/>
   </attribute>
</attribute>

这篇关于如何将具有定义级别的元素序列放入元素结构中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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