xsl-list
[Top] [All Lists]

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

2007-03-08 04:30:17
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>

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

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>
     <organismo txt="5">
        <anuncio txt="6"/>
     </organismo>
     <organismo txt="7">
        <anuncio txt="8"/>
     </organismo>
  </subseccion>
  <subseccion txt="9">
     <organismo txt="10">
        <anuncio txt="11"/>
     </organismo>
  </subseccion>
</seccion>
<seccion txt="12">
  <subseccion txt="13">
     <organismo txt="14">
        <anuncio txt="15"/>
     </organismo>
  </subseccion>
</seccion>

HTH,

Cheers,
-- Abel Braaksma
  http://abelleba.metacarpus.com




--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--