michelqa
michelqa

Reputation: 157

Recursive XSLT transformation with attributes

With the following XML :

<Sections><Section Type="Type1" Text="blabla1"><Section Type="Type2" Text="blabla2"/>  </Section></Sections>

I want to produce the following output :

<Sections><Type1 Text="blabla1"><Type2 Text="blabla2"/></Type1></Sections>

I'm playing with XSLT since many hours, I cant even figure out something to start with... There are many good example on XLST transformation but I'm still missing something about recursivity and using the Type attribute to create my node. How to transform any section node in the document to its corresponing type attribute?

Any tutorial that do something similar , xslt resources or anything to start with whould be great

Thanks

Upvotes: 0

Views: 193

Answers (1)

JLRishe
JLRishe

Reputation: 101652

How's this (as requested in comments, modified to convert in both directions):

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml" indent="yes"/>

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

  <!-- Prevent Type attributes from being copied to the output-->
  <xsl:template match="@Type" />

  <!-- Convert <Section Type="Nnn" ... /> into <Nnn ... /> -->
  <xsl:template match="Section">
    <xsl:element name="{@Type}">
      <xsl:apply-templates select="@* | node()"/>
    </xsl:element>
  </xsl:template>

  <!-- Convert <Nnn .... /> into <Section Type="Nnn" ... /> -->
  <xsl:template match="Sections//*[not(self::Section)]">
    <Section Type="{name()}">
      <xsl:apply-templates select="@* | node()" />
    </Section>
  </xsl:template>

</xsl:stylesheet>

Output when run on your first example:

<Sections>
  <Type1 Text="blabla1">
    <Type2 Text="blabla2" />
  </Type1>
</Sections>

Output when run on your second example:

<Sections>
  <Section Type="Type1" Text="blabla1">
    <Section Type="Type2" Text="blabla2" />
  </Section>
</Sections>

Upvotes: 3

Related Questions