计算不同代码中的唯一值(XSLT 1)

时间:2010-09-08 19:17:06

标签: xml xslt distinct

坚持以下内容,并希望在正确的方向上有一些想法/指针。我有以下XML:

<RecordsCollection>
  <CustomerRecord>
    <customerId>12345</customerId>
    <currency>USD</currency>
  </CustomerRecord>
  <CustomerRecord>
    <customerId>12345</customerId>
    <currency>USD</currency>
  </CustomerRecord>
  <CustomerRecord>
    <customerId>90210</customerId>
    <currency>USD</currency>
  </CustomerRecord>
</RecordsCollection>

我需要完成的是简单地生成一个值,其中包含唯一帐号所包含的唯一货币元素的数量。为了进一步解释,上面的示例包含两个具有相同货币(USD)的相同帐号(12345)的条目,因此它们被计为1,另一个条目也被计为1.因此,上面的示例应该结果在:

<totalCount>2</totalCount>

有关如何实现它的任何想法?我知道如何选择不同的帐号,但我似乎无法解决的问题是如何统计每个帐户中的不同货币。

最后,这必须使用XSLT 1.0来完成......任何想法都会非常感激!

2 个答案:

答案 0 :(得分:0)

此样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key name="kRecordByIdAndCurr" match="CustomerRecord"
             use="concat(customerId,'++',currency)"/>
    <xsl:template match="/">
        <totalCount>
            <xsl:value-of select="count(*/*
                                         [count(.|key('kRecordByIdAndCurr',
                                                      concat(customerId,
                                                             '++',
                                                             currency)
                                                     )[1]
                                               )=1])"/>
        </totalCount>
    </xsl:template>
</xsl:stylesheet>

输出:

<totalCount>2</totalCount>

注意:只需按customerIdcurrency字符串值进行分组。

修改抱歉,错过customerId之前。

答案 1 :(得分:0)

此转化

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:key name="kCurrencyByIdAndType" match="currency"
  use="concat(../customerId, '+', .)"/>

 <xsl:template match="/*">
  <totalCount>
   <xsl:value-of select=
    "count(*/currency[generate-id(key('kCurrencyByIdAndType',
                                      concat(../customerId, '+', .)
                                      )[1]
                                 )
                    = generate-id()
                    ]
          )
    "/>
  </totalCount>
 </xsl:template>
</xsl:stylesheet>

应用于提供的XML文档

<RecordsCollection>
  <CustomerRecord>
    <customerId>12345</customerId>
    <currency>USD</currency>
  </CustomerRecord>
  <CustomerRecord>
    <customerId>12345</customerId>
    <currency>USD</currency>
  </CustomerRecord>
  <CustomerRecord>
    <customerId>90210</customerId>
    <currency>USD</currency>
  </CustomerRecord>
</RecordsCollection>

生成想要的正确结果

<totalCount>2</totalCount>

说明: Muenchian分组方法用于复合键,可以表示为任何currency及其customerId兄弟的字符串值的串联。