user2096168
user2096168

Reputation: 23

XSLT rename XML Tag with parent name

I want to change the following XML:

<command>
    <node>
        <e id="list1">
            <node>
                <e id="01"><key id="value">Value01</key></e>
                <e id="02"><key id="value">Value02</key></e>
            </node>
        </e>
    </node>
    <key>
        <e id="11">Value11</e>
        <e id="12">Value12</e>
    </key>
</command>

To obtain this XML:

<command>
    <node id="list1">
        <node id="01"><key id="value">Value01</key></node>
        <node id="02"><key id="value">Value02</key></node>
    </node>
    <key id="11">Value11</key>
    <key id="12">Value12</key>
</command>

So there are many problems :

I have tried several transformation unsuccessfully (I am a beginner in XSLT). Does anyone have a solution for this transformation? Thanks!

Upvotes: 0

Views: 304

Answers (1)

Martin Honnen
Martin Honnen

Reputation: 167716

Start with

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

then you want to add a template for

<xsl:template match="*[e]">
  <xsl:apply-templates/>
</xsl:template>

and one for

<xsl:template match="e">
  <xsl:element name="{name(..)}">
    <xsl:apply-templates select="@* | node()"/>
  </xsl:element>
</xsl:template>

The complete stylesheet then is

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

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

<xsl:template match="*[e]">
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="e">
  <xsl:element name="{name(..)}">
    <xsl:apply-templates select="@* | node()"/>
  </xsl:element>
</xsl:template>

</xsl:stylesheet>

Upvotes: 3

Related Questions