2015-02-10 88 views
1

我正在嘗試在xml中找到每個元素的xpath並將其作爲元素值進行提取。 我的源文件看起來像:MarkLogic:使用xquery獲取元素的xpath

<root> 
<parent1> 
    <child1></child1> 
    <child2></child2> 
</parent1> 

<parent2> 
    <child1></child1> 
</parent2> 
</root> 

我想要的輸出,如:

<root> 
<parent1> 
    <child1> /root/parent1/child1 </child1> 
    <child2> /root/parent1/child2 </child2> 
</parent1> 

<parent2> 
    <child1> /root/parent2/child1 </child1> 
</parent2> 
</root> 

我目前得到的輸出爲:

<root> 
<parent1> 
<child1> /root/parent1/child1 </child1> 
<child2> /root/parent1/child2 </child2> 
</parent1>" 

<parent2> 
<child1> /root/parent1/parent2/child1 </child1> 
</parent2> 
</root> 

我無法正確地遍歷找到xpath。任何投入都是有價值的。

+0

顯示代碼,即使它是錯誤的,通常讚賞.. – grtjn 2015-02-10 12:24:41

回答

7

我會建議使用xdmp:path,也許是這樣的:

declare function local:add-paths($nodes) { 
    for $node in $nodes 
    return 
    typeswitch ($node) 
    case element() 
     return element { node-name($node) } { 
     $node/@*, 
     if ($node/node()) then 
      local:add-paths($node/node()) 
     else 
     xdmp:path($node) 
     } 
    default 
     return $node 
}; 

let $xml := 
    <root> 
     <parent1> 
      <child1></child1> 
      <child2></child2> 
     </parent1> 

     <parent2> 
      <child1></child1> 
     </parent2> 
    </root> 
return local:add-paths($xml) 

HTH!

+0

非常感謝。它有幫助。 – kol 2015-02-11 03:34:16