[xsl] arbitrary depth element type conversion

Subject: [xsl] arbitrary depth element type conversion
From: Sebastian Tennant <sebyte@xxxxxxxxxxxxxxx>
Date: Fri, 03 Feb 2006 12:12:53 +0000
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