在XSLT中计算不同的项目 [英] Counting distinct items in XSLT

查看:64
本文介绍了在XSLT中计算不同的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的XML:

<assessment>
 <variables>
  <variable>
   <attributes>
    <variable_name value="FRED"/>
   </attributes>
  </variable>
 </variables>
 <variables>
  <variable>
   <attributes>
    <variable_name value="MORTIMER"/>
   </attributes>
  </variable>
 </variables>
 <variables>
  <variable>
   <attributes>
    <variable_name value="FRED"/>
   </attributes>
  </variable>
 </variables>
</assessment>

我知道使用此XSLT:

I know that with this XSLT:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
 <xsl:output method="html"/>

 <xsl:template match="assessment">
  <xsl:for-each select=".//variables/variable/attributes/variable_name">
   <xsl:value-of select="@value"/>
   <br/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

我可以输出以下内容:

FRED 
MORTIMER 
FRED

但是我真正想要输出的是:

But what I really want to output is this:

FRED: 2 
MORTIMER: 1 

也就是说,我想列出不同的元素以及每个元素出现多少次。请注意,我希望元素按其首次出现的顺序出现(这可能会排除一些使用排序的解决方案)。

That is, I want to list the distinct elements and how many times each occurs. Note that I want the elements to appear in the order of their first appearance (which might rule out some solutions that use sorting).

我该怎么做?

推荐答案

此转换

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

 <xsl:key name="kValueByVal" match="variable_name/@value"
  use="."/>

 <xsl:template match="/">
  <xsl:for-each select="
   /*/*/variable/attributes/variable_name/@value
             [generate-id()
             =
              generate-id(key('kValueByVal', .)[1])
             ]
   ">
     <xsl:value-of select=
     "concat(., ' ', count(key('kValueByVal', .)), '&#xA;')"/>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

在应用于提供的XML文档时,会产生所需的正确结果

FRED 2
MORTIMER 1

这篇关于在XSLT中计算不同的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆