david wells
david wells

Reputation: 13

How do I rename an XML element with the value of its first attribute using XSLT?

I am new to XSLT and have XML structures that look like this:

  <Loop LoopId="1000A" Name="SUBMITTER NAME">
  .... a bunch of sub-elements, etc. 
  </Loop>

I am trying to write an XSLT that will convert them all to this: (concatenate the value of the LoopId attribute to its parent element name)

  <Loop1000A LoopId="1000A" Name="SUBMITTER NAME">
  .... a bunch of sub-elements, etc. 
  </Loop1000A>

I have a style sheet that gets me almost all of the way there, but it is getting rid of the attribute LoopId and I don't know why - the style sheet below produces this result:

  <Loop1000A Name="SUBMITTER NAME">
  .... a bunch of sub-elements, etc. 
  </Loop1000A>

Is there a way to modify it so I keep the LoopId attribute?

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

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

  <xsl:template match="@LoopId"/>

  <xsl:template match="*[@LoopId]">
     <xsl:variable name="vRep" select="concat('Loop',@LoopId)"/>
    <xsl:element name="{$vRep}">
      <xsl:apply-templates select="node()|@*"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

Thanks

Upvotes: 1

Views: 222

Answers (2)

Martin Honnen
Martin Honnen

Reputation: 167436

Remove the template <xsl:template match="@LoopId"/> as that way you remove the LoopId attribute.

Upvotes: 1

michael.hor257k
michael.hor257k

Reputation: 116959

Change:

<xsl:element name="concat('Loop', @LoopId)">

to:

<xsl:element name="{concat('Loop', @LoopId)}">

See: https://www.w3.org/TR/xslt/#attribute-value-templates

Upvotes: 1

Related Questions