Re: [xsl] arbitrary depth element type conversion

Subject: Re: [xsl] arbitrary depth element type conversion
From: Mukul Gandhi <gandhi.mukul@xxxxxxxxx>
Date: Fri, 3 Feb 2006 21:47:22 +0530
Please try this stylesheet

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

<xsl:output method="xml" indent="yes" />

<!-- identity template -->
<xsl:template match="node() | @*">
   <xsl:copy>
     <xsl:apply-templates select="node() | @*" />
   </xsl:copy>
</xsl:template>

<xsl:template match="*" priority="1">
   <div class="{name()}">
     <xsl:apply-templates />
   </div>
</xsl:template>

</xsl:stylesheet>

Regards,
Mukul

On 2/3/06, Sebastian Tennant <sebyte@xxxxxxxxxxxxxxx> wrote:
> Hi all,
>
> Given an XML doc:
>
>  <document>
>    <first>
>      first
>      <first-child-of-first>
>        first child of first
>      </first-child-of-first>
>      <second-child-of-second>
>        second child of second
>      </second-child-of-second>
>    </first>
>    <second>
>      second
>      <first-child-of-second>
>        first child of second
>        <first-grandchild-of-second>
>          first grandchild of second
>        </first-grandchild-of-second>
>      </first-child-of-second>
>    </second>
>    <third>
>      third
>    </third>
>    orphan
>  </document>
>
> I would like to preserve the exact same structure but change all the
> elements to divs, with class attributes reflecting the source element
> types, to an arbitrary depth.
>
> I have almost got there with this stylesheet:
>
>  <xsl:template match="document">
>      <xsl:apply-templates select="child::*" />
>  </xsl:template>
>
>  <xsl:template match="*">
>    <xsl:element name="div">
>      <xsl:attribute name="class">
>        <xsl:value-of select="name(.)" />
>      </xsl:attribute>
>      <xsl:value-of select="." />
>      <xsl:apply-templates select="child::*" />
>    </xsl:element>
>  </xsl:template>
>
> but the element contents of child elements are being duplicated in
> parent elements:
>
>  <div class="first">
>    first
>    first child of first
>    second child of second
>    <div class="first-child-of-first">
>      first child of first
>    </div>
>    <div class="second-child-of-second">
>      second child of second
>    </div>
>  </div>
>  <div class="second">
>    second
>    first child of second
>    first grandchild of second
>    <div class="first-child-of-second">
>      first child of second
>      first grandchild of second
>      <div class="first-grandchild-of-second">
>        first grandchild of second
>      </div>
>    </div>
>  </div>
>  <div class="third">
>    third
>  </div>
>
> How can I avoid this?
>
> sdt

Current Thread