数据如下:
<Users> <User id="2" name="ABC" Division="HR"/> <User id="3" name="xyz" Division="Admin"/> <User id="4" name="LMN" Division="Payroll"/> <User id="5" name="PQR" Division="HR"/> </Users>
想要这样的效果:
<AllUsers>
<Division value="HR">
<User>
<id>2</id>
<name>ABC</name>
</User>
<User>
<id>5</id>
<name>PQR</name>
</User>
</Division>
<Division value="ADMIN">
<User>
<id>3</id>
<name>XYZ</name>
</User>
</Division>
<Division value="Payroll">
<User>
<id>4</id>
<name>LMN</name>
</User>
</Division>
</AllUsers>
代码的实现方式:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes" />
<xsl:key name="division" match="User" use="@Division" />
<xsl:template match="Users">
<AllUsers>
<xsl:apply-templates select="User[generate-id(.)=generate-id(key('division',@Division)[1])]"/>
</AllUsers>
</xsl:template>
<xsl:template match="User">
<Division value="@Division">
<xsl:for-each select="key('division', @Division)">
<User>
<id>
<xsl:value-of select="@id" />
</id>
<name>
<xsl:value-of select="@name" />
</name>
</User>
</xsl:for-each>
</Division>
</xsl:template>
</xsl:stylesheet>