MarkLogic:使用xquery获取元素的xpath

时间:2021-10-17 07:53:20

I am trying to find the xpath of every element in an xml and put it up as the element value. My source file would look like :

我试图找到xml中每个元素的xpath,并将其作为元素值。我的源文件如下:

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

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

I wanted an output like:

我希望输出如下:

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

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

I am currently getting an output as:

我现在得到的输出是:

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

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

I am unable to traverse properly to find the xpath. Any input would be valuable.

我无法正确地遍历以找到xpath。任何投入都是有价值的。

1 个解决方案

#1


7  

I would suggest using xdmp:path, maybe like this:

我建议使用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!

HTH !

#1


7  

I would suggest using xdmp:path, maybe like this:

我建议使用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!

HTH !