declare function local:depth-first( $graph as element(graph), $start as xs:integer ) as item()* { let $map := local:depth-first( $graph, $start, map{ 'visited':=(), 'payload':=() } ) return $map('payload') }; declare function local:depth-first( $graph as element(graph), $current as xs:integer, $state as map(*) ) as map(*) { let $node := $graph/node[@id = $current] return fold-left( function($state, $child) { let $id as xs:integer := $child/@idref return if($id = $state('visited')) then $state else local:depth-first($graph, $id, $state) }, map{ 'visited':=($state('visited'), $current), 'payload':=($state('payload'), $node/@name/string()) }, $node/child ) }; local:depth-first( , 10 )