Page 1 of 1

XSLT to transform to CSV

Posted: Fri Sep 02, 2016 11:11 am
by Terkelsen
I'm trying to use XSLT transform in Switch to convert an XML-file into CSV. I don't know much about XSLT stylesheets, but I managed to find and manipulate this to work for converting my XML to HTML. Could any of you help to make this convert to CSV rather than HTML?

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Bestilling</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:left">Emne</th>
<th style="text-align:left">Navn</th>
</tr>
<xsl:for-each select="textfile/name-value-pair">
<tr>
<td>
<xsl:value-of select="name"/>
</td>
<td>
<xsl:value-of select="value"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

Re: XSLT to transform to CSV

Posted: Fri Sep 02, 2016 2:54 pm
by loicaigon
Hi Terkelsen,

Try this. I just presume the source html file as a regular table with headers and row data. I am joining both files.

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:strip-space elements="*" />
<xsl:output method="text" encoding="UTF-8" indent="no" omit-xml-declaration="yes" />
<xsl:template match="//body">
        
        <xsl:apply-templates select="//table"/>
    </xsl:template>
    
    
    <xsl:template match="table">
        <xsl:apply-templates select="//tr/th | //tr/td"/>
    </xsl:template>
    
    
    <xsl:template match="th|td">
        <xsl:value-of select="."/>
        <xsl:choose >
            <xsl:when test="./following-sibling::*!=''">
                <xsl:text>	</xsl:text>
            </xsl:when>
            <xsl:when test="position()=last()"></xsl:when>
            <xsl:otherwise>
                <xsl:text>&#xA;</xsl:text>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
    
</xsl:stylesheet>
HTH

Loic
http://www.ozalto.com/

Re: XSLT to transform to CSV

Posted: Fri Sep 02, 2016 4:37 pm
by Terkelsen
Thanks a lot, Loic, for your effort. However, my input is an xml-file rather than html. Or actually it's originally an e-mail injected as text and converted to xml using the app TXT pickup.

Meanwhile I found this, which seems to do the job:

Code: Select all

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/">
  <xsl:apply-templates select="textfile"/>
</xsl:template>

<xsl:template match="/">
  <xsl:for-each select="textfile/name-value-pair">
    <xsl:value-of select="name"/>:
    <xsl:value-of select="value"/>
    <xsl:if test="position() != last()">
      <xsl:value-of select="','"/>
      
    </xsl:if>
  </xsl:for-each>
  <xsl:text>&#10;</xsl:text>
</xsl:template>

</xsl:stylesheet>