Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML to CSV Using XSLT

Tags:

xml

csv

xslt

I have the following XML document:

<projects>   <project>    <name>Shockwave</name>     <language>Ruby</language>     <owner>Brian May</owner>     <state>New</state>     <startDate>31/10/2008 0:00:00</startDate>    </project>   <project>    <name>Other</name>     <language>Erlang</language>     <owner>Takashi Miike</owner>     <state> Canceled </state>     <startDate>07/11/2008 0:00:00</startDate>    </project> ... 

And I'd like to get this from the transformation (XSLT) result:

Shockwave,Ruby,Brian May,New,31/10/2008 0:00:00 Other,Erlang,Takashi Miike,Cancelled,07/11/2008 0:00:00 

Does anyone know the XSLT to achieve this? I'm using .net in case that matters.

like image 666
Pablo Fernandez Avatar asked Dec 13 '08 15:12

Pablo Fernandez


People also ask

Can XSLT transform XML to CSV?

The following XSL Style Sheet (compatible with XSLT 1.0) can be used to transform the XML into CSV. It is quite generic and can easily be configured to handle different xml elements by changing the list of fields defined ar the beginning.

How XSLT works with XML?

XSLT is used to transform XML document from one form to another form. XSLT uses Xpath to perform matching of nodes to perform these transformation . The result of applying XSLT to XML document could be an another XML document, HTML, text or any another document from technology perspective.

Can XSLT transform XML to JSON?

XSLTJSON: Transforming XML to JSON using XSLTXSLTJSON is an XSLT 2.0 stylesheet to transform arbitrary XML to JavaScript Object Notation (JSON). JSON is a lightweight data-interchange format based on a subset of the JavaScript language, and often offered as an alternative to XML in—for example—web services.


1 Answers

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:output method="text" encoding="utf-8" />    <xsl:param name="delim" select="','" />   <xsl:param name="quote" select="'&quot;'" />   <xsl:param name="break" select="'&#xA;'" />    <xsl:template match="/">     <xsl:apply-templates select="projects/project" />   </xsl:template>    <xsl:template match="project">     <xsl:apply-templates />     <xsl:if test="following-sibling::*">       <xsl:value-of select="$break" />     </xsl:if>   </xsl:template>    <xsl:template match="*">     <!-- remove normalize-space() if you want keep white-space at it is -->      <xsl:value-of select="concat($quote, normalize-space(), $quote)" />     <xsl:if test="following-sibling::*">       <xsl:value-of select="$delim" />     </xsl:if>   </xsl:template>    <xsl:template match="text()" /> </xsl:stylesheet> 
like image 188
Tomalak Avatar answered Sep 21 '22 19:09

Tomalak