Search code examples
xslt

Making a tree from delimited elements using XSLT


The question is similar to this one but slightly more complex...

I need to transform a flat XML like

    <XML>
        <A.W>1</A.W>
        <A.X>2</A.X>
        <B.Y>3</B.Y>
        <B.Z>4</B.Z>
        <C>5</C>
    </XML>

to a proper tree

    <XML>
        <A>
            <W>1</W>
            <X>2</X>
        </A>
        <B>
            <Y>3</Y>
            <Z>4</Z>
        </B>
        <C>5</C>
    </XML>

using XSLT

So, the levels of the tree are dot-separated. Ideally with unlimited fold, but could be just the 2-levels one. Thank you!


Solution

  • Try this for starters:

    <xsl:template match="XML">
       <xsl:for-each-group select="*" 
                group-adjacent="substring-before(local-name(), '.')">
         <xsl:element name="{current-grouping-key()}">
            <xsl:for-each select="current-group()">
               <xsl:element name="{substring-after(local-name(), '.')}">
                   <xsl:copy-of select="child::node()"/>
               </xsl:element>
            </xsl:for-each>
         </xsl:element>
      </xsl:for-each-group>
    </xsl:template>