xsl-list
[Top] [All Lists]

Re: arbitrary depth element type conversion

2006-02-03 09:17:22
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(_at_)smolny(_dot_)plus(_dot_)com> 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

--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--



<Prev in Thread] Current Thread [Next in Thread>