Re: [xsl] Another problem from Flat XML File to Hierarchical

Subject: Re: [xsl] Another problem from Flat XML File to Hierarchical
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Mon, 12 Feb 2007 17:18:50 +0100
Hi Alex,

You didn't tell us what XSLT version you are using. I try with XSLT 2. Somehow I often have trouble with even rather flat to hierarchical questions. I am sure somebody else can do much better. The below solution works correctly if you add 'level1' to the top of your input xml. If you don't want that, you should adjust the patterns a bit:


<xsl:template match="/"> <xsl:for-each-group select="$data/*" group-starting-with="level1">

       <xsl:copy>
           <xsl:apply-templates select="current-group()[2]" />
       </xsl:copy>
   </xsl:for-each-group>
</xsl:template>

<xsl:template match="*[matches(name(), 'level')]">
   <xsl:variable name="currentname" select="name()" />
   <xsl:for-each-group
       select="current-group()[position() > 1]"
       group-starting-with="*[name() = $currentname]">

       <xsl:copy>
           <xsl:apply-templates select="current-group()[2]" />
       </xsl:copy>
   </xsl:for-each-group>
</xsl:template>


It's a variant to the tree-traversal technique, as it always selects one higher than the current node.


Hope this helps,

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


alex v. wrote:
I have a flat xml like this:

<level2></level2>
<level3></level3>
<level2></level2>
<level1></level1>
<level2></level2>
<level3></level3>
<level3></level3>

and I need to transform in a hierarchy structure like this using the
tag name as key:

<level2>
<level3></level3>
</level2>
<level2></level2>
<level1>
<level2>
<level3></level3>
<level3></level3>
</level2>
</level1>


Thanks in advance.


~av

Current Thread