如何计算节点中的不同值? [英] How to count distinct values in a node?
问题描述
如何在 XSLT 中计算节点中的不同值?
How to count distinct values in a node in XSLT?
示例:我想计算 Country 节点中现有国家/地区的数量,在本例中为 3.
Example: I want to count the number of existing countries in Country nodes, in this case, it would be 3.
<Artists_by_Countries>
<Artist_by_Country>
<Location_ID>62</Location_ID>
<Artist_ID>212</Artist_ID>
<Country>Argentina</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>108</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>4</Location_ID>
<Artist_ID>111</Artist_ID>
<Country>Australia</Country>
</Artist_by_Country>
<Artist_by_Country>
<Location_ID>12</Location_ID>
<Artist_ID>78</Artist_ID>
<Country>Germany</Country>
</Artist_by_Country>
</Artists_by_Countries>
推荐答案
如果您有一个大文档,您可能想使用通常用于分组的Muenchian Method"来识别不同的节点.声明一个键,用不同的值索引你想要计数的东西:
If you have a large document, you probably want to use the "Muenchian Method", which is usually used for grouping, to identify the distinct nodes. Declare a key that indexes the things you want to count by the values that are distinct:
<xsl:key name="artists-by-country" match="Artist_by_Country" use="Country" />
然后您可以使用以下方法获取具有不同国家/地区的
元素:
Then you can get the <Artist_by_Country>
elements that have distinct countries using:
/Artists_by_Countries
/Artist_by_Country
[generate-id(.) =
generate-id(key('artists-by-country', Country)[1])]
并且您可以通过将其包装在对 count()
函数的调用中来计算它们.
and you can count them by wrapping that in a call to the count()
function.
当然在 XSLT 2.0 中,就这么简单
Of course in XSLT 2.0, it's as simple as
count(distinct-values(/Artists_by_Countries/Artist_by_Country/Country))
这篇关于如何计算节点中的不同值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!