Remove duplicates from return XQuery

Peter Fašianok picture Peter Fašianok · Jun 1, 2013 · Viewed 9k times · Source

My XQuery is:

declare namespace xsd="http://www.w3.org/2001/XMLSchema"; 
for $schema in xsd:schema
for $nodes in $schema//*,
    $attr in $nodes/xsd:element/@name
where fn:contains($attr,'city')
return $attr

return: name="city" name="city" name="city" name="city" name="city"

When I add distinct-values like:

declare namespace xsd="http://www.w3.org/2001/XMLSchema"; 
for $schema in xsd:schema
for $nodes in $schema//*,
    $attr in $nodes/xsd:element/@name
where fn:contains($attr,'city')
return distinct-values($attr)

return: city city city city city

I need only one "city", how can I do it ?

Answer

Christian Grün picture Christian Grün · Jun 1, 2013

You need to apply the distinct-values function on the whole result (i. e., not to each single result item):

declare namespace xsd="http://www.w3.org/2001/XMLSchema"; 
distinct-values(
  for $schema in xsd:schema
  for $nodes in $schema//*,
      $attr in $nodes/xsd:element/@name
  where fn:contains($attr,'city')
  return $attr
)

The query can also be written as a single XPath expression:

distinct-values(//xs:element/@name[contains(., 'city')])