RE: [xsl] transform from flat to hierarchical

Subject: RE: [xsl] transform from flat to hierarchical
From: "Ken Tam" <kentam@xxxxxxxxxxxxxxx>
Date: Tue, 28 Nov 2006 21:17:11 -0800
Hi David,

Thanks for your reply. This is definitely enough to get me started. Let me
know if you can think of a way to check for nested elements as described.

Thanks,
Ken

-----Original Message-----
From: David Carlisle [mailto:davidc@xxxxxxxxx]
Sent: Monday, November 27, 2006 6:09 AM
To: xsl-list@xxxxxxxxxxxxxxxxxxxxxx
Subject: Re: [xsl] transform from flat to hierarchical



This doesn't check for nested elements with the same name eg "a"
containing a "sub a" but it could probably be made to do that.
I wrote it as a 2.0 sheet but actually didn't use any 2.0 features and
it works in 1.0 unchanged.

I'm not sure I have the predicates quite right still, but they work on
the example posted, and should be enough to get you started.

David


<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform";>

<xsl:output indent="yes"/>

<xsl:template match="logs">
  <logs>
    <xsl:apply-templates select="log[1]"/>
  </logs>
</xsl:template>

<xsl:template match="log">
  <log name="{.}">
    <xsl:apply-templates
select="following-sibling::log[1][starts-with(.,'sub ')]"/>
  </log>
  <xsl:apply-templates
select="following-sibling::log[1][not(starts-with(.,'sub
'))][not(starts-with(.,'end of '))]"/>
</xsl:template>

<xsl:template match="log[starts-with(.,'sub ')]">
  <xsl:variable name="n" select="substring-after(.,'sub ')"/>
  <log name="{$n}">
    <xsl:apply-templates select="following-sibling::log[1]"/>
  </log>
  <xsl:apply-templates select="following-sibling::log[.=concat('end of
',$n)]"/>
</xsl:template>

<xsl:template match="log[starts-with(.,'end of')]">
  <xsl:apply-templates select="following-sibling::log[1]"/>
</xsl:template>

</xsl:stylesheet>


$ saxon8 log.xml log.xsl
<?xml version="1.0" encoding="UTF-8"?>
<logs>
   <log name="a">
      <log name="b">
         <log name="c">
            <log name="d">
               <log name="e"/>
               <log name="f"/>
            </log>
            <log name="g"/>
         </log>
      </log>
      <log name="h"/>
      <log name="i"/>
   </log>
</logs>

Current Thread