Question

I have an XML file with the following entries:

<file>
 <unit id="u-1.01"/>
 <unit id="u-1.02"/>
 <unit id="u-1.03"/>
 <unit id="u-1.04"/>
 <unit id="u-1.05"/>
 <unit id="u-1.06"/>
 <unit id="u-1.07"/>
 <unit id="u-2.01"/>
 <unit id="u-2.02"/>
 <unit id="u-2.03"/>
 <unit id="u-2.04"/>
 <unit id="u-2.05"/>
 <unit id="u-2.06"/>
</file>

I want to count the number of distinct-values using the query below.

The query goes through each of the @id attributes and selects the third character in the string.

declare function local:count-base-pages($basefile) {
for $identifiers in $basefile/unit/@id
let $id := distinct-values(substring($identifiers, 3, 1)) 
return count($id) 
};

However, this query returns the following sequence:

1 1 1 1 1 1 1 2 2 2 2 2 2

The wished outcome would be 2 because there are two distinct values: 1 and 2.

How am I misusing the distinct-values and count functions?

Was it helpful?

Solution

You need to wrap your functions around the actual FLWOR expression: count(distinct-values(for ... return ...))

OTHER TIPS

Use the shorter:

count(distinct-values(/*/*/@id/substring(.,3,1)))

Performing the above XQuery on the provided XML document:

<file>
 <unit id="u-1.01"/>
 <unit id="u-1.02"/>
 <unit id="u-1.03"/>
 <unit id="u-1.04"/>
 <unit id="u-1.05"/>
 <unit id="u-1.06"/>
 <unit id="u-1.07"/>
 <unit id="u-2.01"/>
 <unit id="u-2.02"/>
 <unit id="u-2.03"/>
 <unit id="u-2.04"/>
 <unit id="u-2.05"/>
 <unit id="u-2.06"/>
</file>

produces the wanted, correct result:

2
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top