Some hints:
Don't bother with
where
clauses where you can filter down earlier, in a specifier retrieving your content.If you want to have only one
<result>
, rather than one per datum, you need to start it before the FLWOR expression; whatever you 'return' will be returned once per item.
This is an example of something closer:
<result>{
for $large-country in doc("abc")//country[@population > 20000]
let $large-cities := $country/city[population > 3500]
return
<country name="{$large-country/@name}">
<num_cities>{count($large-cities)}</num_cities>
</country>
}</result>