一,这是一个简单的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>
II。下面是一个类似的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>
你叫什么终止条件。你需要做的是,有一个函数,递归地调用它自己的值,如1,1.1,1.2,1.3 .. 1.nnn然后,为他们每个人再次调用1.1.1,1.1.2等。每个系列必须在您的预定义条件下结束。 –
优化可以首先收集所有属性,按照您需要的顺序排列它们,然后只调用那些属性,因此您的终止不会被硬编码。 –