Question

I'd link to transform XML with attributes like the 'name' attribute in the following:

<books>
  <book name="TheBumperBookOfXMLProgramming"/>
  <book name="XsltForDummies"/>
</books>

into elements called what was in the name attribute:

<books>
  <TheBumperBookOfXMLProgramming/>
  <XsltForDummies/>
</books>

using XSLT. Any ideas?

Was it helpful?

Solution

You can create elements by name using xsl:element:

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

  <xsl:template match="/">
    <books>
      <xsl:apply-templates />
    </books>

  </xsl:template>

  <xsl:template match="book">
    <xsl:element name="{@name}" />
  </xsl:template>

</xsl:stylesheet>

OTHER TIPS

<xsl:template match="book">
   <xsl:element name="{@name}">
       <xsl:copy-of select="@*[name()!='name'] />
   </xsl:element>
</xsl:template>

this also copies over any properties on <book> not named 'name'

<book name="XsltForDummies" id="12" />

will turn into

<XsltForDummies id="12 />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top