XSLT分组多个密钥

时间:2015-05-09 00:46:47

标签: xml xslt

我正在使用XSLT 1.0,并尝试按我的XML中的两个元素进行分组。基本上我想转换以下XML:

<requirements>
  <item>
    <category>Admin</category>
    <functionality>View Data</functionality>
    <requirement>The system shall do 1</requirement>
  </item>
  <item>
    <category>Admin</category>
    <functionality>View Data</functionality>
    <requirement>The system shall do 2</requirement>
  </item>
  <item>
    <category>Admin</category>
    <functionality>Query Data</functionality>
    <requirement>The system shall do 3</requirement>
  </item>
  <item>
    <category>Admin</category>
    <functionality>Query Data</functionality>
    <requirement>The system shall do 4</requirement>
  </item>
</requirements>

进入这个:

<requirements>
  <item>
    <category>Admin</category>
    <functionality>View Data</functionality>
    <requirement id ="1">The system shall do 1</requirement>
    <requirement id ="2">The system shall do 2</requirement>
  </item>
  <item>
    <category>Admin</category>
    <functionality>Query Data</functionality>
    <requirement id="1">The system shall do 3</requirement>
    <requirement id="2">The system shall do 4</requirement>
  </item>
</requirements>

我还没有足够的XSLT经验来正确实现Muenchian方法。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

如果您使用连接categoryfunctionality的密钥,就像<xsl:key name="group" match="item" use="concat(category, '|', functionality)"/>一样,那么您可以使用正常的Muenchian分组:

<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output indent="yes"/>

<xsl:key name="group" match="item" use="concat(category, '|', functionality)"/>

<xsl:template match="requirements">
  <xsl:copy>
    <xsl:apply-templates select="item[generate-id() = generate-id(key('group', concat(category, '|', functionality))[1])]"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="item">
  <xsl:copy>
    <xsl:copy-of select="category | functionality"/>
    <xsl:apply-templates select="key('group', concat(category, '|', functionality))/requirement"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="requirement">
  <xsl:copy>
    <xsl:attribute name="id"><xsl:value-of select="position()"/></xsl:attribute>
    <xsl:apply-templates/>
  </xsl:copy>
</xsl:template>

</xsl:stylesheet>