Re: [xsl] Transforming a non-hierarchical XML into a hierarchical one

Subject: Re: [xsl] Transforming a non-hierarchical XML into a hierarchical one
From: Abel Braaksma <>
Date: Thu, 08 Mar 2007 12:28:26 +0100
SEXpeare wrote:
I'm using 2.0 luckily, and I must admit that i'm totally lost on this
task, I have done simple approaches that haven't done anything useful.

Hi 'SEXpeare',

Here's a solution that does the trick. I don't often deal with grouping problems and most of the time let others on this list answer them, but now I thought it's time to tackle it myself. I tried an open-mind approach and I did not check with the "best practices" that I should be aware of. It is simple enough and it does the trick, but I don't like the 'copy-of' I use to decouple the current-group from the input stream (if you don't do that, you will find that 'following-sibling' also takes the nodes outside the current-group into account). I am sure there must be a better solution.

Here it is (assuming $input contains your input document):

<xsl:template match="/" name="main">
   <xsl:apply-templates select="$input/sumario/seccion[1]" />

<xsl:template match="*">
<xsl:variable name="name" select="name()" />
select="self::* | following-sibling::*"
group-starting-with="*[name() = $name]">
<xsl:copy-of select="@*" />
<xsl:variable name="group" >
<xsl:copy-of select="current-group()" />
<xsl:apply-templates select="$group/*[2]" />

It outputs, with Saxon 8.8, the following (I numbered the txt attributes to be sure to have original nodes and no extra copies)
<seccion txt="1">
<subseccion txt="2">
<organismo txt="3">
<anuncio txt="4"/>
<organismo txt="5">
<anuncio txt="6"/>
<organismo txt="7">
<anuncio txt="8"/>
<subseccion txt="9">
<organismo txt="10">
<anuncio txt="11"/>
<seccion txt="12">
<subseccion txt="13">
<organismo txt="14">
<anuncio txt="15"/>


-- Abel Braaksma

Current Thread