3

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
brabster
  • 42,504
  • 27
  • 146
  • 186
  • Both the answers below are valid. @divo's is exactly what I asked, @Martin's is an additional consideration to bear in mind. Thanks to both :) – brabster Mar 30 '09 at 15:47
  • Why do you want to do this? It doesn't make a lot of sense. – AmbroseChapel Mar 31 '09 at 05:15
  • @Ambrose - curiosity? Also, it seems more straightforward to define an XMLSchema for the latter. – brabster Mar 31 '09 at 12:47
  • The whole point of XML/HTML etc is that the markup is supposed to define the content. Not BE the content. What's the difference between your idea and a plain-text file with book names in it? – AmbroseChapel Apr 01 '09 at 11:30
  • @Ambrose - the example provided removes anything not relevant to the question. In reality there would be content, and I want to tranform between 'element centric' and 'attribute centric' XML (as in http://stackoverflow.com/questions/241819/xml-best-practices-attributes-vs-additional-nodes) – brabster Apr 02 '09 at 11:15

2 Answers2

4

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>
Dirk Vollmar
  • 172,527
  • 53
  • 255
  • 316
  • This leaves open the possibility of creating invalid xml (read: not xml) because the character set is more restricted with element names. – pc1oad1etter Aug 24 '10 at 17:59
  • @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) – Dirk Vollmar Aug 24 '10 at 20:49
3
<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
  • 13,476
  • 44
  • 63