如何计算节点中的不同值?

Dan*_*ira 13 xml xslt xslt-grouping

如何计算XSLT中节点中的不同值?

示例:我想计算Country节点中现有国家/地区的数量,在这种情况下,它将为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>
Run Code Online (Sandbox Code Playgroud)

Jen*_*niT 27

如果您有一个大文档,您可能希望使用通常用于分组的"Muenchian方法"来识别不同的节点.声明一个键,用于通过不同的值索引要计数的事物:

<xsl:key name="artists-by-country" match="Artist_by_Country" use="Country" />
Run Code Online (Sandbox Code Playgroud)

然后,您可以<Artist_by_Country>使用以下不同国家/地区获取元素:

/Artists_by_Countries
  /Artist_by_Country
    [generate-id(.) =
     generate-id(key('artists-by-country', Country)[1])]
Run Code Online (Sandbox Code Playgroud)

你可以通过在count()函数调用中包装它来计算它们.

当然在XSLT 2.0中,它就像它一样简单

count(distinct-values(/Artists_by_Countries/Artist_by_Country/Country))
Run Code Online (Sandbox Code Playgroud)


sam*_*son 6

在XSLT 1.0中,这并不明显,但以下内容应该让您了解需求:

count(//Artist_by_Country[not(Location_ID=preceding-sibling::Artist_by_Country/Location_ID)]/Location_ID)
Run Code Online (Sandbox Code Playgroud)

XML中的元素越多,所需的时间就越长,因为它会检查每个元素的每个前面的兄弟元素.


Chr*_*org 5

尝试这样的事情:

count(//Country[not(following::Country/text() = text())])
Run Code Online (Sandbox Code Playgroud)

"给我所有国家节点的计数,没有跟随国家和匹配的文本"

该表达式的有趣位IMO是跟随轴.

您也可以删除第一个/text(),然后替换第二个.

  • 不,它会一直有效.follow ::适用于整个文档,如果在具有相同值的上下文之后有任何国家/地区,则该节点将不计算在内. (3认同)