kol
kol

Reputation: 106

MarkLogic: Getting xpath of an element using xquery

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 :

<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.

Upvotes: 1

Views: 764

Answers (1)

grtjn
grtjn

Reputation: 20414

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

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!

Upvotes: 7

Related Questions