Thursday, April 28, 2011

How can I transform an element attribute to an element name in XSLT?

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?

From stackoverflow
  • 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>
    
    pc1oad1etter : This leaves open the possibility of creating invalid xml (read: not xml) because the character set is more restricted with element names.
    0xA3 : @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)
  • <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 />
    

0 comments:

Post a Comment