[XSL-LIST Mailing List Archive Home] [By Thread] [By Date]

Re: [xsl] transform from flat to hierarchical


Subject: Re: [xsl] transform from flat to hierarchical
From: David Carlisle <davidc@xxxxxxxxx>
Date: Mon, 27 Nov 2006 14:09:06 GMT

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