user1961077
user1961077

Reputation: 3

XML transform recursive and attribute as node name

I am having XML files in below format.

<Main>
    <root>
        <group firstname="daniel" secondname="creig">
            <a firstname="tin" secondname="tao"/>
                <b firstname="bella" secondname="james">
                    <c firstname="khadhar" secondname="abdul">
                        <d firstname="xiang" secondname="tin"/>
                    </c>
                </b>
        </group>
    </root>
</Main>

And I am trying to get the output like below.

<members>
    <member><id>group</id><firstname>daniel</firstname><secondname>creig</secondname></member>
    <member><id>a</id><firstname>tin</firstname><secondname>tao</secondname></member>
    <member><id>b</id><firstname>bella</firstname><secondname>james</secondname></member>
    <member><id>c</id><firstname>khadhar</firstname><secondname>abdul</secondname></member>
    <member><id>d</id><firstname>xiang</firstname><secondname>tin</secondname></member>
</members>

So far My XSL will be looking like this.

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

<!-- Elements Section -->
<xsl:template match="/*/root/*">
<member>
    <id>
        <xsl:value-of select="local-name()" />  
    </id>
    <attr>
        <xsl:apply-templates select="@*" /> 
    </attr>
</member>
</xsl:template>

<xsl:template match="@*">
    <xsl:element name="{local-name()}">
        <xsl:value-of select="(.)" />
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

All i need is to convert the nodes in XML tree of any depth to an array. Thanks in Advance.

Upvotes: 0

Views: 719

Answers (1)

JLRishe
JLRishe

Reputation: 101652

How's this:

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

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

<xsl:template match="root//*">
    <member>
       <id><xsl:value-of select="local-name(.)" /></id>
       <xsl:apply-templates select="@*" />
    </member>
    <xsl:apply-templates select="*" />
</xsl:template>

<xsl:template match="root//@*">
    <xsl:element name="{local-name(.)}">
       <xsl:value-of select="." />
    </xsl:element>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions