2013-10-01 19 views
11

即时通讯仍在学习for-each-group使用XSL分组类似的最佳方式是什么?(按国家)我试图使用XSL将此XML转换为另一种XML。如何使用XSL中的每个组

<?xml version="1.0" encoding="UTF-8"?> 
<Person> 
    <Student> 
     <Info Country="England" Name="Dan" Age="20" Class="C" /> 
    </Student> 
    <Student> 
     <Info Country="England" Name="Dan" Age="20" Class="B" /> 

    </Student> 
    <Student> 
     <Info Country="England" Name="Sam" Age="20" Class="A" /> 
    </Student> 

    <Student> 
     <Info Country="Australia" Name="David" Age="22" Class="D" /> 
    </Student> 
    <Student> 
     <Info Country="Australia" Name="David" Age="22" Class="A" /> 
    </Student> 

</Person> 
+0

要看你想在群。你想如何看待你的结果?分组在“国家”或分组在“名称”或“班级”或组合? –

回答

27

如果您按国家进行分组,您可以从例如:

<xsl:template match="Person"> 
    <xsl:for-each-group select="Student/Info" group-by="@Country"> 
    <country name="{current-grouping-key()}"> 

    </country> 
    </xsl:for-each-group> 
</xsl:template> 

然后,你必须决定是否要进一步组每个国家组中的Info元素,例如通过名称:

<xsl:template match="Person"> 
    <xsl:for-each-group select="Student/Info" group-by="@Country"> 
    <country name="{current-grouping-key()}"> 
     <xsl:for-each-group select="current-group()" group-by="@Name"> 
     <student name="{current-grouping-key()}"> 
      <classes> 
      <xsl:for-each select="current-group()"> 
       <class><xsl:value-of select="@Class"/></class> 
      </xsl:for-each> 
      </classes> 
     </student> 
     </xsl:for-each-group> 
    </country> 
    </xsl:for-each-group> 
</xsl:template>