views:

150

answers:

2

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?

+3  A: 

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"&gt;
  <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>
0xA3
This leaves open the possibility of creating invalid xml (read: not xml) because the character set is more restricted with element names.
pc1oad1etter
@pc1oad1etter: How is it more restricted? As far as I know both are names according to this [production rule](http://www.w3.org/TR/REC-xml/#NT-Name)
0xA3
+3  A: 
<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 />
Martijn Laarman