【问题标题】:How to use group by in xslt如何在 xslt 中使用 group by
【发布时间】:2010-02-25 12:31:56
【问题描述】:

我有一个 xml,它有很多元素,其中大部分都包含属性。因为某些属性值是相同的,所以我需要对它们进行分组并生成 diff xml。 I/p 例如:

<TestNode>
 <ABC1 value="10.7" format="$" />
 <ABC2 value="10.5" format="$" />
 <ABC3 value="20" format="Rs" />
 <ABC4 value="50" format="Rs" />
 <ABC5 value="10.5" format="$" />
</TestNode>

我需要按格式对行进行分组。 注意:格式不固定...可能会增长... O/P 示例: 有可能得到吗?提前谢谢...

【问题讨论】:

  • 您使用的是 XSLT 1.0 还是 XSLT 2.0 ?
  • 我使用的是 xslt 1.0。 2.0 在 VS 2008 中可用吗?
  • Microsoft 没有 XSLT 2.0 实现。 Saxon.NET 实现可从 www.saxonica.com 获得。

标签: xslt group-by


【解决方案1】:

在 XSLT 1.0 中,您将使用 Muenchian 分组。

定义一个键“格式”,我们可以从中轻松选择给定格式名称的所有元素。而不是应用 Muenchian 分组来查找输入中的唯一格式。

然后它就变得简单了。 “*”模板将针对每种格式应用一次,并使用 key() 获取该格式的所有条目。

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

    <xsl:output method="xml" indent="yes" />

    <xsl:key name="format" match="TestNode/*" use="@format" />

    <xsl:template match="TestNode">
        <body>
            <xsl:apply-templates select="*[generate-id(.)=generate-id(key('format',@format)[1])]"/>
        </body>
    </xsl:template>

    <xsl:template match="*">
        <format format="{@format}">
          <xsl:copy-of select="key('format', @format)" />
        </format>
    </xsl:template>

</xsl:stylesheet>

【讨论】:

    【解决方案2】:

    在 XSLT 2.0 中,您应该可以使用 &lt;xsl:for-each-group&gt;current-grouping-key()current-group() 来完成此操作

    例子:

    <xsl:for-each-group 
        select="TestNode/*"
        group-by="@format"
    >
        <group format="{current-grouping-key()}">
            <xsl:for-each select="current-group()">
                <xsl:copy-of select="."/>
            </xsl:for-each>
        </group>
    </xsl:for-each-group>
    

    见:http://www.w3.org/TR/xslt20/#grouping

    【讨论】:

    • xsl:for-each-group 上的属性称为 'group-by' 而不是 'groupby'。以及为什么 for-each 复制组中的每个项目,为什么不简单地 而不是 for-each?
    • Martin,感谢您指出 group by 中的错字。我希望我提供的规范链接不会浪费在所有逐字复制我的建议的人身上。至于for-each,其想法是建议如何访问组中的各个项目。确实,如果您只想复制这些项目,那么是的,您确实可以只使用一个复制人。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多