[xsl] for-each(-group) - flattening a set of strings hierarchy

Subject: [xsl] for-each(-group) - flattening a set of strings hierarchy
From: Robert Koberg <rob@xxxxxxxxxx>
Date: Thu, 22 Jan 2009 23:10:18 -0500
Hi, (didn't really know how to phrase the subject... :) )

Given an XML instance like:

    <mapping resource="a/b/A.xml"/>
    <mapping resource="a/b/B.xml"/>
    <mapping resource="a/b/c/A.xml"/>
    <mapping resource="a/b/c/B.xml"/>
    <mapping resource="d/e/A.xml"/>
    <mapping resource="d/e/B.xml"/>

I want to get output as (javascript namespaces):

var a = {};
a.b = {};
a.b.c = {};

var d = {};
d.e = {};

I am clumsily getting about half of the way there, but I feel like I am approaching it wrong. I am imagining a bunch of for loops.

Here is what I am outputting so far with the XSL below (don't really care about the whitespace at this point):

var a.b = {};
a.b.c = {};
d.e = {};

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; version="2.0" xmlns:xs="http://www.w3.org/2001/XMLSchema";>
<xsl:output method="text"/>

<xsl:template match="/">

    <xsl:variable name="resources" as="xs:string*">
      <xsl:sequence select="q/a//mapping/@resource"/>

<xsl:variable name="packages" as="xs:string*">
<xsl:for-each-group select="$resources"
remove(tokenize(., '/'), count(tokenize(., '/')))
, '/')
<xsl:sequence select="translate(current-grouping-key(), '/', '.')"/>

    <xsl:for-each-group select="$packages" group-by=".">
      <xsl:if test="position()=1">var </xsl:if>
      <xsl:value-of select="current-grouping-key()"/> = {};<xsl:text>


thanks for any help,

Current Thread