How to handle recursion in XQuery?

旧城冷巷雨未停 提交于 2019-12-03 08:39:57

Your checks with $reachedCountries only guarantee that countries do not appear twice on the same path, but you still visit every country along every possible path, which takes a long time. There is no loop, just lots of redundancy.

Here is a simple depth-first search that does what you want:

declare function local:dfs($stack, $seen) {
  if(empty($stack)) then $seen
  else (
    let $country := $stack[1]
    let $neighbors :=
        for $code in $country/border/@country[not(. = $seen/@car_code)]
        return $country/../country[@car_code = $code]
    return local:dfs(($neighbors, $stack[position() > 1]), ($seen, $neighbors))
  )
};

local:dfs(doc('mondial.xml')//country[@car_code = 'S'], ())/name
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!