I. 这是一个简单的 XSLT 2.0 解决方案(类似的 XSLT 1.0 解决方案紧随其后):
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:my="my:my">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*">
<xsl:sequence select="my:grouping(*, 1)"/>
</xsl:template>
<xsl:function name="my:grouping" as="element()*">
<xsl:param name="pNodes" as="element()*"/>
<xsl:param name="pLevel" as="xs:integer"/>
<xsl:if test="$pNodes">
<xsl:for-each-group select="$pNodes" group-by="tokenize(@id, '\.')[$pLevel]">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:sequence select="
my:grouping(current-group()[tokenize(@id, '\.')[$pLevel+1]], $pLevel+1)"/>
</xsl:copy>
</xsl:for-each-group>
</xsl:if>
</xsl:function>
</xsl:stylesheet>
当将此转换应用于此 XML 文档(提供的 XML 片段,包装在单个顶部元素中以使其成为格式良好的 XML 文档)时:
<t>
<item id="1"/>
<item id="1.1"/>
<item id="1.1.1"/>
<item id="1.1.2"/>
<item id="1.1.2.1"/>
<item id="1.2"/>
<item id="1.3"/>
</t>
产生了想要的正确结果:
<item id="1">
<item id="1.1">
<item id="1.1.1"/>
<item id="1.1.2">
<item id="1.1.2.1"/>
</item>
</item>
<item id="1.2"/>
<item id="1.3"/>
</item>
二、这是一个类似的 XSLT 1.0 解决方案:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:strip-space elements="*"/>
<xsl:key name="kFollowing" match="item"
use="generate-id(preceding-sibling::*
[string-length(current()/@id) > string-length(@id)
and
starts-with(current()/@id, concat(@id, '.'))]
[1])"/>
<xsl:template match="/*">
<xsl:call-template name="grouping">
<xsl:with-param name="pNodes" select="*"/>
<xsl:with-param name="pLevel" select="1"/>
</xsl:call-template>
</xsl:template>
<xsl:template name="grouping">
<xsl:param name="pNodes"/>
<xsl:param name="pLevel" select="1"/>
<xsl:for-each select=
"$pNodes[$pLevel > string-length(@id) - string-length(translate(@id, '.', ''))]">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:call-template name="grouping">
<xsl:with-param name="pNodes" select="key('kFollowing', generate-id())"/>
<xsl:with-param name="pLevel" select="$pLevel+1"/>
</xsl:call-template>
</xsl:copy>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
当这个 XSLT 1.0 转换应用于同一个文档(上图)时,会产生同样想要的正确结果:
<item id="1">
<item id="1.1">
<item id="1.1.1"/>
<item id="1.1.2">
<item id="1.1.2.1"/>
</item>
</item>
<item id="1.2"/>
<item id="1.3"/>
</item>