Jayant
Jayant

Reputation: 152

Renaming all element tags with name attribute by attribute value

<IPECReactorLabel Name="Label" id= "someId">
      <IPECCodeName Name="CodeName">
        <String Name="Name" type="product">NH3</String>
        <String Name="Location">INLET</String>
        <String Name="GIPSValueType">REC</String>
      </IPECCodeName>
      <IPECReactorType Name="ReactorType">
        <String>NH3</String>
        <String Name="DesignCode">S-200</String>
      </IPECReactorType>
 </IPECReactorLabel>

Not all elements in the above xml has Name attribute. What I wud like to achieve through XSLT is keep the entire xml as same but change the element tag by the value of its Name attribute. If an element doesnt contain a Name attribute, then the element tag should remain unchanged. So the final xml wud like:

<Label id= "someId">
<CodeName>
  <Name type="product">NH3</Name>
  <Location>INLET</Location>
  <GIPSValueType>REC</GIPSValueType>
</CodeName>
<ReactorType>
  <String>NH3</String>
  <DesignCode>S-200</DesignCode>
</ReactorType>
</Label>

I am new to XSLT. Thanks in advance for the help

Upvotes: 0

Views: 611

Answers (1)

Tim C
Tim C

Reputation: 70598

Start off with the XSLT identity template, which on its own will copy all nodes unchanged

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

This means, you only need to write templates from the nodes you wish to change. In this case, elements with a `@Name' attribute.

 <xsl:template match="*[@Name]">

In this, you can then create a new element using the xsl:element construct.

 <xsl:element name="{@Name}">

Note the use of Attribute Value Templates here. The curly braces indicate an expression to be evaluated to generate the new element name.

Try this XSLT

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

    <xsl:template match="*[@Name]">
      <xsl:element name="{@Name}">
        <xsl:apply-templates select="@*[name() != 'Name']|node()"/>
      </xsl:element>
    </xsl:template>

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

Upvotes: 3

Related Questions