Skip to Content
XSLT
book

XSLT

by Doug Tidwell
August 2001
Intermediate to advanced
480 pages
11h 16m
English
O'Reilly Media, Inc.
Content preview from XSLT

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" ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning XSLT

Learning XSLT

Michael Fitzgerald
Inside XSLT

Inside XSLT

Steven Holzner
XSLT Cookbook

XSLT Cookbook

Sal Mangano

Publisher Resources

ISBN: 0596000537Supplemental ContentCatalog PageErrata