home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  


Book HomeXSLSearch this book

D.2. How Do I Convert All Attributes to Elements?

Here's a short stylesheet that does the job:

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
  <xsl:output method="xml"/>

  <xsl:template match="*">
    <xsl:element name="{name()}">
      <xsl:for-each select="@*">
        <xsl:element name="{name()}">
          <xsl:value-of select="."/>
        </xsl:element>
      </xsl:for-each>
      <xsl:apply-templates select="*|text()"/>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

This example is about as short a stylesheet as you'll ever see. The XSLT processor uses the single <xsl:template> to process every element in the document. For each element, we output:

  • A new element, whose name is the name of the current element

  • For each attribute of the current element (selected with @*), a new element whose name is the name of the current attribute. The text of our newly created element is the text of the current attribute.

Once we've processed all the attributes, we process all of the child elements and text nodes beneath the current element. Processing them in this way means that the text and generated elements in the output document will be in the same sequence in the original document and the generated one.

As an example, we'll use our stylesheet to transform this XML document:

<?xml version="1.0"?> 
<report> 
  <title>Database Access Sample</title> 
  <section> 
    <title>Employees by Last Name</title> 
    <dbaccess driver="COM.ibm.db2.jdbc.app.DB2Driver" 
      database="jdbc:db2:sample" tablename="wstkadmin.employee" where="*" 
      fieldnames='lastname as "Last Name", 
      firstnme as "First Name", workdept as "Department"' 
      order-by="lastname" group-by="lastname, firstnme, workdept"/> 
  </section> 
</report>

When we transform our document, here are the results:

<?xml version="1.0" encoding="UTF-8"?> 
<report> 
  <title>Database Access Sample</title> 
  <section> 
    <title>Employees by Last Name</title> 
    <dbaccess> 
      <driver>COM.ibm.db2.jdbc.app.DB2Driver</driver> 
      <database>jdbc:db2:sample</database> 
      <tablename>wstkadmin.employee</tablename> 
      <where>*</where> 
      <fieldnames>lastname as "Last Name", firstnme as "First Name", 
        workdept as "Department"</fieldnames> 
      <order-by>lastname</order-by> 
      <group-by>lastname, firstnme, workdept</group-by> 
    </dbaccess> 
  </section> 
</report>

In the output, all attributes of the original document are now elements. (We've added line breaks and indenting to make the output more readable.) With that exception, everything else in the document is unchanged.



Library Navigation Links

Copyright © 2002 O'Reilly & Associates. All rights reserved.