Search code examples
xmlxpathxpath-1.0

XPath 1.0 COUNT - Unique values


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.


Solution

  • 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)])