Invert via a sequence of names by Chris Wallace

functions to convert between a seq of names and a stick, + reverse()

XQuery

declare function local:stick_to_seq($stick) {
   if ($stick)
   then (name($stick),local:stick_to_seq($stick/*))
   else ()
};

declare function local:seq_to_stick($seq) {
   if (exists($seq))
   then element {$seq[1]} {local:seq_to_stick(subsequence($seq,2))}
   else ()
};

declare function local:invert($stick) {
   local:seq_to_stick(reverse(local:stick_to_seq($stick)))
};

let $x := <a><b><c><d/></c></b>/</a>
return local:invert($x)

Result

<d>
    <c>
        <b>
            <a/>
        </b>
    </c>
</d>