user898465
user898465

Reputation: 944

Xquery for determining all nodes are unique

Assuming a document such as:

<a>
 <b>TEST1</b>
 <b>TEST2</b>
 <b>TEST1</b>
</a>

Is there any Xquery one liner you can use to check that all values of b are unique without having to run a for-each of on the doc? So for example in the above document it would return false, whereas in the below document it would return true

<a>
 <b>TEST1</b>
 <b>TEST2</b>
 <b>TEST3</b>
</a>

Upvotes: 1

Views: 159

Answers (3)

Michael Kay
Michael Kay

Reputation: 163458

The most efficient is probably

count(b) = count(distinct-values(b))

The other solutions you have been given are likely to be quadratic in the number of test elements, whereas this is likely to be O(n log n).

(However, this is on the assumption that duplicates are rare. If duplicates are very common, then some kind of fold operation might find them faster, especially with XQuery 3.0).

Upvotes: 0

har07
har07

Reputation: 89305

Similar approach but using empty() might be a bit more efficient :

empty(/a/b[. = following-sibling::b])

empty() returns true if the parameter expression yields empty sequence, and returns false otherwise. So in this case, if there found sibling b with the same value a.k.a a dupe, empty() will return false.

Upvotes: 1

hr_117
hr_117

Reputation: 9627

You can look for sibling with same value e,g:

 count(b[preceding-sibling::b = .])

or to get true or false:

not(b[preceding-sibling::b = .])

Upvotes: 0

Related Questions