3

Given the XML snippet:

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

How do I transform the element <E8> into <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>

2 Answers 2

3

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 on the provided XML document:

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

produces the wanted, correct result:

<transactions>
   <tran id="1">
      <event type="E8">
         <datestamp>2012-05-17T15:16:57Z</datestamp>
      </event>
   </tran>
</transactions>
Sign up to request clarification or add additional context in comments.

Comments

2

Use:

<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>

4 Comments

Thanks, that answers my question, but it's not quite the output I was expecting (see edit). I still need to keep all child elements of the E8 element (there can be more than one). Sorry for not clarifying.
I figured it out. Used <xsl:copy-of select="@*|node()" /> instead of <xsl:value-of select="."/>
@JordanDedels, actually, using xsl:copy-of isn't the best solution -- if in the future you'd need to transform these children, then you'll have to remove this instruction.
@DimitreNovatchev, That's a good point. I'm new to XLST, so thanks for the heads up. I'll use the <xsl:apply-templates/> as shown in your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.