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" ...

Get XSLT now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.