使用XSLT 1.0对多个属性进行分组

时间:2012-07-16 05:49:56

标签: xml xslt xpath xslt-1.0

输入XML:

<?xml version="1.0" encoding="ISO-8859-1"?>

<document>
  <section name="foo" p="Hello from section foo" q="f" w="fo1"/>
  <section name="foo" p="Hello from section foo1" q="f1" w="fo1"/>
  <section name="bar" p="Hello from section bar" q="b" w="ba1"/>
  <section name="bar" p="Hello from section bar1" q="b1" w="ba1"/>
</document>

预期输出XML:

<document>
  <section name="foo" w= "fo1">
      <contain p="Hello from section foo" q="f" />
      <contain p="Hello from section foo1" q="f1" />
  </section>
  <section name="bar" w= "ba1">
      <contain p="Hello from section bar" q="b" />
      <contain p="Hello from section bar1" q="b1" />
  </section>
</document>

我的应用程序只能使用XSLT 1.0,因此我无法使用xsl:for-each-group

1 个答案:

答案 0 :(得分:2)

使用:

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

  <xsl:key name="k" match="section" use="@name"/>
  <xsl:output method="xml" indent="yes"/>

  <xsl:template match="/document">
    <xsl:copy>
      <xsl:apply-templates select="section[generate-id() = generate-id(key('k', @name))]"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="section">
    <xsl:copy>
      <xsl:copy-of select="@name | @w"/>
      <xsl:for-each select="key('k', @name)">
        <contain p="{@p}" q="{@q}"/>
      </xsl:for-each>
    </xsl:copy>
  </xsl:template>
</xsl:stylesheet>