Thomas Byrne
Thomas Byrne

Reputation: 137

Change Element name to that of one of its Attribute - XSLT/ XML

Using XSLT I'd like to change an XML Element name to that of one of its Attribute (the element will only contain one attribute) and also to remove the attribute.

I have an XML document which looks like this:

<EVENTS>
  <EVENT TYPE="XXXXXX">
    <ID>1</ID>
    <STATUS>COM</STATUS>
  </EVENT>
  <EVENT TYPE="XXXXXX">
    <ID>2</ID>
    <STATUS>ACC</STATUS>
  </EVENT>
  <EVENT TYPE="YYYYYY">
    <ID>3</ID>
    <STATUS>COM</STATUS>
  </EVENT>
  <EVENT TYPE="ZZZZZZ">
    <ID>4</ID>
    <STATUS>COM</STATUS>
  </EVENT>
  <EVENT TYPE="XXXXXX">
    <ID>5</ID>
    <STATUS>DEL</STATUS>
  </EVENT>
</EVENTS>

I'd like to transform the document to looks like this:

<EVENTS>
  <XXXXXX>
    <ID>1</ID>
    <STATUS>COM</STATUS>
  </XXXXXX>
  <XXXXXX>
    <ID>2</ID>
    <STATUS>ACC</STATUS>
  </XXXXXX>
  <YYYYYY>
    <ID>3</ID>
    <STATUS>COM</STATUS>
  </YYYYYY>
  <ZZZZZZ>
    <ID>4</ID>
    <STATUS>COM</STATUS>
  <ZZZZZZ>
  <XXXXXX>
    <ID>5</ID>
    <STATUS>DEL</STATUS>
  </XXXXXX>
</EVENTS>

Upvotes: 0

Views: 495

Answers (2)

Thomas Byrne
Thomas Byrne

Reputation: 137

Excellent, thanks for your help! For completeness I used the following and it worked....

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:template match="EVENT">
      <xsl:element name="{@TYPE}">
          <xsl:copy-of select="*"/>
     </xsl:element>
  </xsl:template>
</xsl:stylesheet>

Upvotes: 0

user663031
user663031

Reputation:

You're looking for the <xsl:element> command, which in this case you'd use as in

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

This uses an attribute value template, which allows string expressions inside curly braces.

Then arrange to not copy through the TYPE attribute.

Upvotes: 1

Related Questions