Search code examples
xmlxsltxpathxpath-1.0

Count Distinct Content in XPath 1.0


Given the following XML

<Address>
 <CountryName>France</CountryName>
</Address>
...
<Address>
 <CountryName>Germany</CountryName>
</Address>
...
<Address>
 <CountryName>Spain</CountryName>
</Address>

How can I count the number of distinct countries using XPath 1.0?

The list of addresses is very long and contains many distinct countries so I want to avoid having to express each one specifically.


Solution

  • Select the count of all the CountryName elements who's value is not the same value as the CountryName elements that are children of the current CountryName element's parent's following-siblings that are Address elements:

    count(//Address/CountryName[not(.=../following-sibling::Address/CountryName)])