Thursday, September 5

Transform XML to CSV with XSLT

Introduction: XSLT  is often used to transform XML  to CSV  which can be easily imported to database.

An example of XML document (contact.xml) is shown below:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="contact.xsl"?>

<Contacts>
<Contact>
<FirstName>Fran</FirstName>
<LastName>Smith</LastName>
<Address>1278 N. Michigan Ave.</Address>
<City>Chicago</City>
<State>IL</State>
<Zip>69007</Zip>
<Phone>312-276-3765</Phone>
</Contact>
<Contact>
<FirstName>Kathy</FirstName>
<LastName>Lobo</LastName>
<Address>333 Lindsay Street</Address>
<City> Oakbrook</City>
<State>IL</State>
<Zip>60056</Zip>
<Phone>630-287-4532</Phone>
</Contact>
</Contacts>

Here is the XSLT (contact.xsl) that translates contact.xml to  CSV.

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns="http://www.w3.org/1999/xhtml">
<xsl:template match="/">
<html>
<table>
<!--Loop the columns in order-->
<xsl:for-each select="Contacts/Contact">
<tr><td>
<!-- Extract the column value-->
<xsl:value-of select="FirstName"/>
<xsl:value-of select="','"/>
<xsl:value-of select="LastName"/>
<xsl:value-of select="','"/>
<xsl:value-of select="Address"/>
<xsl:value-of select="','"/>
<xsl:value-of select="City"/>
<xsl:value-of select="','"/>
<xsl:value-of select="State"/>
<xsl:value-of select="','"/>
<xsl:value-of select="Zip"/>
<xsl:value-of select="','"/>
<xsl:value-of select="Phone"/>
</td></tr>
</xsl:for-each>
</table>
</html>
</xsl:template>
Output:
Fran,Smith,1278 N. Michigan Ave.,Chicago,IL,69007,312-276-3765 
Kathy,Lobo,333 Lindsay Street, Oakbrook,IL,60056,630-287-4532 

No comments:

Post a Comment