xsl-list
[Top] [All Lists]

Re: [xsl] Transforming XML to CSV

2008-01-10 04:34:12
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


--~------------------------------------------------------------------
XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list
To unsubscribe, go to: http://lists.mulberrytech.com/xsl-list/
or e-mail: <mailto:xsl-list-unsubscribe(_at_)lists(_dot_)mulberrytech(_dot_)com>
--~--

<Prev in Thread] Current Thread [Next in Thread>