Re: [xsl] most efficient flat file listing to hierarchical

Subject: Re: [xsl] most efficient flat file listing to hierarchical
From: George Cristian Bina <george@xxxxxxxxxxxxx>
Date: Thu, 11 Jan 2007 15:50:37 +0200
Here it is another solution, XSLT 2.0, that uses a key that maps from the folder to the items contained in that folder, then it is enough to start from empty folder and just iterate the items in each folder.

<?xml version="1.0" encoding="US-ASCII"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; version="2.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"; xmlns:f="http://www.oxygenxml.com/functions";
exclude-result-prefixes="xs f">
<xsl:output indent="yes"/>


  <xsl:function name="f:baseFolder">
    <xsl:param name="value" as="xs:string"/>
    <xsl:variable name="tokens" select="tokenize($value, '/')"/>
    <xsl:value-of select="$tokens[position()!=last()]" separator="/"/>
  </xsl:function>
  <xsl:key name="folder" match="item" use="f:baseFolder(.)"/>

  <xsl:template match="listing">
    <dir>
      <xsl:call-template name="list"/>
    </dir>
  </xsl:template>

  <xsl:template name="list">
    <xsl:param name="folder" select="''"/>
    <xsl:for-each select="key('folder', $folder)">
      <xsl:choose>
        <xsl:when test="key('folder', .)">
          <dir name="{translate(substring-after(., $folder), '/', '')}">
            <xsl:call-template name="list">
              <xsl:with-param name="folder" select="."/>
            </xsl:call-template>
          </dir>
        </xsl:when>
        <xsl:otherwise>
          <file name="{translate(substring-after(., $folder), '/', '')}"/>
        </xsl:otherwise>
      </xsl:choose>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>

Regards,
George
---------------------------------------------------------------------
George Cristian Bina
<oXygen/> XML Editor, Schema Editor and XSLT Editor/Debugger
http://www.oxygenxml.com

Current Thread