I observed in a project where I use XQuery quite extensively, that I ended up programming functions that would construct intermediate XML structures containing parts of a document, and that other functions would 'break down' these intermediate structures again to construct the final result. For example, one function would construct a list of all combinations of children of two elements, a subsequent function would filter the combinations, and from that a final result is constructed. Observe that construction of all combinations means heavy duplication (due to copy semantics of element construction). Also observe that the intermediary structures are not really necessary: element construction and subsequent XPath navigation could cancel eachother out. How to find the possible cancellations is a hard nut to crack. Avoiding unnecessary duplication is another. Some meaningless example: declare function allCombinations($wlists as element(wlist)*) as element(wlist)* { let $cnt := count($wlists) return if ($cnt eq 0) then () else if ($cnt eq 1) then for $x in $wlists/child::w return {$x} else let $y := exactly-one($wlists[1]) ,$ys := $wlists[position() gt 1] ,$as := allCombinations($ys) return for $x in $y/child::w, $a in $as return {$x}{$a/child::w} }; declare function filter($wlists as element(wlist)*) as element(wlist)* { for $wl in $wlists where count($wl/*[1]/foo) eq 1 return $wl }; declare function result($wlists as element(wlist)*) { for $wl in $wlists let $f := exactly-one($wl/*[1]/foo) return {$f/*}{$wl/*[position() gt 1]/*} }; let $exA := (,

) return result(filter(allCombinations($exA)))