This is a following up question to question to "Select all of an element between the current element and the next of the current element". Even If I'm not sure if creating a new question is the right way I do it anyway. Because the original question was answered but changed afterwards. So in my view the changed questions is open. Also I think the changed question should be put back in the stat were it fit to the answer.
The question is how to create an hierarchical xml form an "flat" xml like a book description.
The input xml is something like
<root>
<heading_1>Section 1</heading_1>
<para>...</para>
<list_1>...</list_1>
<heading_2>Section 1.1</heading_2>
<para>...</para>
<heading_3>Section 1.1.1</heading_3>
<para>...</para>
<list_1>...</list_1>
<heading_2>Section 1.2</heading_2>
<para>...</para>
<footnote>...</footnote>
<heading_1>Section 2</heading_1>
<para>...</para>
<list_1>...</list_1>
<heading_2>Section 2.1</heading_2>
<para>...</para>
<list_1>...</list_1>
<list_2>...</list_2>
<heading_3>Seciton 2.1.1</heading_3>
<para>...</para>
<heading_2>Section 2.2</heading_2>
<para>...</para>
<footnote>...</footnote>
</root>
Each <heading_*>
should be interpreted as start of an <section>
The expected output xml is.
<section>
<title>Section 1</title>
<para>...</para>
<list_1>...</list_1>
<section>
<title>Section 1.1</title>
<para>...</para>
<section>
<title>Section 1.1.1</title>
<para>...</para>
<list_1>...</list_1>
</section>
</section>
<section>
<title>Section 1.2</title>
<para>...</para>
<footnote>...</footnote>
</section>
</section>
<section>
<title>Section 2</title>
<para>...</para>
<list_1>...</list_1>
<section>
<title>Section 2.1</title>
<para>...</para>
<list_1>...</list_1>
<list_2>...</list_2>
<section>
<title>Section 2.1.1</title>
<para>...</para>
</section>
</section>
<section>
<title>Section 2.2</title>
<para>...</para>
<footnote>...</footnote>
</section>
</section>
Also I tried a while to find a solution for this bases on the original solution from @JLRishe. So I found one and like to put it here as answer as one possibility. And I hope for a more comprehensible solution.
Here is a generic solution that will work for any heading depth:
When run on your sample input, this produces:
Here my current solution
It will generate the following output: