2012-05-17...">

How to convert XML element name to attribute value using XSLT?

Given the XML snippet:

<transactions>
  <tran id="1">
    <E8>
      <datestamp>2012-05-17T15:16:57Z</datestamp>
    </E8>
  </tran>
</transactions>

      

How do I convert an element <E8>

to <event type="E8">

using XSLT?

Edit: Expected output:

<transactions>
  <tran id="1">
    <event type="E8">
      <datestamp>2012-05-17T15:16:57Z</datestamp>
    </event>
  </tran>
</transactions>

      

+3


source to share


2 answers


Using:

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

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

  <xsl:template match="tran/*">
    <event type="{name()}">
      <xsl:value-of select="."/>

    </event>
  </xsl:template>

</xsl:stylesheet>

      



Output:

<transactions>
  <tran id="1">
    <event type="E8">2012-05-17T15:16:57Z</event>
  </tran>
</transactions>

      

+2


source


This transformation :

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

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

 <xsl:template match="tran/E8">
  <event type="E8">
   <xsl:apply-templates/>
  </event>
 </xsl:template>
</xsl:stylesheet>

      

when applied to the provided XML document:



<transactions>
  <tran id="1">
    <E8>
      <datestamp>2012-05-17T15:16:57Z</datestamp>
    </E8>
  </tran>
</transactions>

      

produces the desired, correct result:

<transactions>
   <tran id="1">
      <event type="E8">
         <datestamp>2012-05-17T15:16:57Z</datestamp>
      </event>
   </tran>
</transactions>

      

+3


source







All Articles