A Tech Log

October 1, 2008

XSLT to Convert XML Elements to Attributes

Filed under: Development — adallow @ 4:01 am
Tags:

David Carlisle has a good script:

If you want to convert the following from this:

<atom  phase="gas">
   <name>Hydrogen</name>
   <symbol>H</symbol>
   <boiling_point units="Kelvin">20.28</boiling_point>
</atom>

To this:
<atom phase="gas" name="Hydrogen" symbol="H">
    <boiling_point units="Kelvin">20.28</boiling_point>
</atom>

Then the following XSLT can help:

<?xml version=’1.0′ encoding=’utf-8′?>
<xsl:stylesheet version=’1.0′ xmlns:xsl=’http://www.w3.org/1999/XSL/Transform&#8217; xmlns:msxsl=’urn:schemas-microsoft-com:xslt’ exclude-result-prefixes=’msxsl’>
<xsl:template match=’*’>
<xsl:copy>
<xsl:for-each select=’@*|*[not(* or @*)]’>
<xsl:attribute name='{name(.)}’><xsl:value-of select=’.’/>
</xsl:attribute>
</xsl:for-each>
<xsl:apply-templates select=’*[* or @*]|text()’/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>

Blog at WordPress.com.