Marklogic - 如何在 Xquery 中分配动态变量

Marklogic - How to assign dynamic variable in Xquery

我试过下面提到的 XQuery。

declare variable $path  as xs:string :="D:\Mongo\";

    let $uri :="/MJ/1932/Vol1/Part1/387.xml"
    let $x := fn:normalize-space(fn:replace($uri,"/"," "))
    for $i in fn:tokenize($x, " ")
    let $j := fn:concat($path,$i)
    return($j)

实际产量

    D:\Mongo\MJ
    D:\Mongo32
    D:\Mongo\Vol1
    D:\Mongo\Part1
    D:\Mongo7.xml

预期输出

D:\Mongo\MJ
D:\Mongo\MJ32
D:\Mongo\MJ32\Vol1
D:\Mongo\MJ32\Vol1\Part1
D:\Mongo\MJ32\Vol1\Part17.xml

请给我建议,如何更改动态变量值。

XQuery 是一种函数式编程语言,这意味着变量是不可变的。您不能简单地增加或附加到已定义的变量。通常,使用递归函数来构造结果。

这个例子(还有更简洁的例子,我想保持各个部分分开并且简单易懂)递归创建路径,每次执行时附加另一个级别。 $path 前缀是单独附加的,以免混淆不同的任务。

declare variable $path  as xs:string :="D:\Mongo\";
declare variable $uri as xs:string := "/MJ/1932/Vol1/Part1/387.xml";

declare function local:add-path($parts as xs:string*) as xs:string* {
  let $head := $parts[1]
  let $tail := $parts[position() > 1]
  return
    if ($head)
    then (
      $head,
      for $path in local:add-path($tail)
      return string-join(($head, $path), "\")
    )
    else ()

};

for $uri in local:add-path(fn:tokenize(fn:normalize-space(fn:replace($uri,"/"," ")), " "))
return concat($path, $uri)

在这种特定情况下,另一种方法是遍历位置计数器并将零件连接到此位置:

declare variable $path  as xs:string :="D:\Mongo\";
declare variable $uri as xs:string := "/MJ/1932/Vol1/Part1/387.xml";

let $parts := fn:tokenize(fn:normalize-space(fn:replace($uri,"/"," ")), " ")
for $i in (1 to count($parts))
return concat($path, string-join($parts[position() <= $i], '\'))