PaulM
PaulM

Reputation: 375

Sorting a tree with xquery by local-name

I want the below XML
<a>
<z>
   <e>
   <b>
<c>

Sorted as such    
<a>
<c>
<z>
   <b>
   <e>

I am using local-name as order by. I believe I will need to call function recursively. I believe I will need to recreate the element using element constructor.

I do not care about attributes at this time. snippet:

let $child-elements := $elements/*
return
    if ($child-elements) then
        myfunctx:sort($child-elements, $current-element)
    else 
        element { xs:Qname ($local-name)} , {$current-element, $result) ???

Upvotes: 1

Views: 56

Answers (1)

Mads Hansen
Mads Hansen

Reputation: 66723

declare function local:sort($container){
  element {$container/name()} {
    for $child in $container/*
    order by $child/local-name()
    return local:sort($child)
  }
};

let $doc := <doc>
  <a/>
  <z>
    <e/>
    <b/>
  </z>
  <c/>
</doc>
return local:sort($doc)

Upvotes: 1

Related Questions