2016-03-28 67 views
1

我已經嘗試過下面提到的XQuery。Marklogic - 如何在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 

請給我建議,如何更改動態變量的值。

回答

4

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], '\')) 
+0

由於延ERAT,其工作的罰款。 – Antony