Re: [xsl] Transforming XML to CSV

Subject: Re: [xsl] Transforming XML to CSV
From: Abel Braaksma <abel.online@xxxxxxxxx>
Date: Thu, 10 Jan 2008 12:33:45 +0100
Adam Lipscombe wrote:
Folks


Firstly apologies if this a no-brainer, I am an XSL beginner.

Np, we all started one day ;)


We have an XML output file that we need to convert into CSV for some customers.
Can this be done with a Transform?

Yes, quite easily. Make sure you set the xsl:output to method="text":


<xsl:output method="text" />

Are there any good examples of how one might approach it?

That of course highly depends on how your XML looks like (all XML is different). You will have to define it yourself. In general, your XSLT will look something like this:


<xsl:output method="text" />

<xsl:template match="/">
   <!-- starting point for root node -->
   <!-- put your header line for the CSV here -->
   <xsl:apply-templates select="my-names/row" />
</

<xsl:template match="row">
   <xsl:apply-templates select="field" />
   <!-- newline at end of each row -->
   <xsl:text>&#xa;</xsl:text>
</

<xsl:template match="field">
    <!-- each field -->
    <xsl:value-of select="." />

    <!-- only output comma separator if not at last field -->
    <xsl:if test="position() != last()">
        <xsl:text>,</xsl:text>
    </xsl:if>
</


The above works with an input something like:


<my-names>
   <row>
       <field>Abel</field>
       <field>Braaksma</field>
   </row>
   <row>
       <field>John</field>
       <field>Doe</field>
   </row>
</my-names>

and will output something like:

Abel,Braaksma
John,Doe


HtH,


Cheers,
-- Abel Braaksma

Current Thread