XPath 1.0 COUNT - Unique values

2019-08-31 00:26发布

问题:

I've got this test XML:

<test>
    <x a="1">
      <x a="2">
        <x>
          <y>y31</y>
          <y>y32</y>
        </x>
      </x>
    </x>
    <x a="1">
      <x a="2">
        <y>y31</y>
        <y>y32</y>
      </x>
    </x>
    <x a="1">
      <y>y11</y>
      <y>y12</y>
    </x>
    <x>
      <y>y11</y>
      <y>y11</y>
    </x>
</test>

How can I query:

1 - All values for y

y32, y32, y11, y12

2 - Number of values for y

I'm trying to use COUNT but I can't count the number of UNIQUE values y has, for example if I run query against sample XML described before I need the result to be 4.

回答1:

If all you've got to work with is XPath (and not XSLT or something of that nature), then I think this is the best you can do:

All distinct y values:

//y[not(. = preceding::y)]

Number of distinct y values:

count(//y[not(. = preceding::y)])