如何使用xslt模板从中获取:
<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,我尝试了不同的分组,但我不知道如何进行递归。
答案 0 :(得分:2)
如果您使用的是应用for-each-group group-starting-with
的功能,则
<?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>