Marklogic-如何在Xquery中分配动态变量 [英] Marklogic - How to assign dynamic variable in Xquery
问题描述
我尝试了下面提到的XQuery.
I have tried below mentioned 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:\Mongo\1932
D:\Mongo\Vol1
D:\Mongo\Part1
D:\Mongo\387.xml
预期输出
D:\Mongo\MJ
D:\Mongo\MJ\1932
D:\Mongo\MJ\1932\Vol1
D:\Mongo\MJ\1932\Vol1\Part1
D:\Mongo\MJ\1932\Vol1\Part1\387.xml
请建议我,如何更改动态变量值.
Please Suggest me , how to change the dynamically variable value.
推荐答案
XQuery是一种功能编程语言,它暗示变量是不可变的.您不能简单地增加或附加到已定义的变量.通常,使用递归函数来构造结果.
XQuery is a functional programming language, which implies variables are immutable. You cannot simply increment or append to a defined variable. Typically, a recursive function is used instead to construct the result.
此示例(有更多简洁的示例,我想使各个部分分开并易于理解)以递归方式创建路径,每次执行时都附加一个级别. $path
前缀是单独添加的,以免混淆不同的任务.
This examples (there are more concise ones, I wanted to keep the individual parts split apart and simple to understand) recursively creates the path, appending another level each time executed. The $path
prefix is appended separately to not mix up the different tasks.
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)
在这种情况下,另一种方法是在位置计数器上循环并将零件连接到该位置:
In this specific case, an alternative would be to loop over a position counter and join the parts up to this position:
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], '\'))
这篇关于Marklogic-如何在Xquery中分配动态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!