I have a list of elements with information about how deep they are located in an XML tree. The elements at "the bottom," i.e. those elements that occur before an element with a lower depth, contain text.
<input>
<text n="x" xml:id="a" depth="1"/>
<div xml:id="b" depth="2"/>
<div xml:id="c" depth="3"/>
<p xml:id="e" depth="4">text</p>
<p xml:id="d" depth="4">text</p>
<p xml:id="x" depth="4">text</p>
<div xml:id="f" depth="3"/>
<lg xml:id="j" depth="4"/>
<l xml:id="k" depth="5">text</l>
<l xml:id="l" depth="5">text</l>
<p xml:id="n" depth="3">text</p>
</input>
I would like to reconstitute this as the XML tree below, in one operation.
<text n="x" xml:id="a" depth="1">
<div xml:id="b" depth="2">
<div xml:id="c" depth="3">
<p xml:id="e" depth="4">text</p>
<p xml:id="d" depth="4">text</p>
<p xml:id="x" depth="4">text</p>
</div>
<div xml:id="f" depth="3">
<lg xml:id="j" depth="4">
<l xml:id="k" depth="5">text</l>
<l xml:id="l" depth="5">text</l>
</lg>
</div>
<p xml:id="n" depth="3">text</p>
</div>
</text>
I think I need to start with the elements of the highest depth, i.e. with all elements of depth 5, and then wrap them up in the preceding element of depth 5-1, and so on, but I can't get my head around how to recurse through this.
The @xml:ids are just for reference.
My question is the converse of my earlier stackoverflow question. It resembles this stackoverflow question, but I need to use XQuery.