如何计算节点中的不同值?
时间:2020-03-06 14:55:25 来源:igfitidea点击:
如何计算XSLT中节点中的不同值?
示例:我想计算"国家/地区"节点中的现有国家/地区数,在这种情况下为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>
解决方案
尝试这样的事情:
count(//Country[not(following::Country/text() = text())])
"给我所有没有以下具有匹配文本的国家/地区的国家/地区节点的数量"
IMO是该表达式有趣的部分。
我们可能还可以删除第一个/ text()
,然后将第二个替换为.
。
在XSLT 1.0中,这并不明显,但是以下内容应使我们对该需求有所了解:
count(//Artist_by_Country[not(Location_ID=preceding-sibling::Artist_by_Country/Location_ID)]/Location_ID)
XML中的元素越多,花费的时间就越长,因为它会检查每个元素的每个在前同级。
如果我们可以在国家/地区首次出现时控制xml的生成,则可以向国家/地区节点添加属性,例如distinct ='true',将该国家/地区标记为"已使用",并且如果随后遇到该属性,则不添加此属性再次国家。
然后你可以做
<xsl:for-each select="Artists_by_Countries/Artist_by_Country/Country[@distinct='true']" />
如果我们有大型文档,则可能要使用通常用于分组的" Muenchian方法"来标识不同的节点。声明一个键,该键通过不同的值对要计数的事物进行索引:
<xsl:key name="artists-by-country" match="Artist_by_Country" use="Country" />
然后,我们可以使用以下方法获取具有不同国家/地区的<Artist_by_Country>元素:
/Artists_by_Countries /Artist_by_Country [generate-id(.) = generate-id(key('artists-by-country', Country)[1])]
我们可以通过将其包装在对count()
函数的调用中来对它们进行计数。
当然,在XSLT 2.0中,它就像
count(distinct-values(/Artists_by_Countries/Artist_by_Country/Country))