Reputation: 491
I have the following xsl file to produce the cd data in csv format:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/catalog">
<xsl:for-each select="cd">
<xsl:apply-templates/>
<xsl:if test="position() = last()"><xsl:value-of select="./child::*"/>, </xsl:if>
<xsl:if test="position() = last()"><xsl:value-of select="./child::year"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Here is the sample data:
<?xml version="1.0" encoding="UTF-8"?>
<catalog>
<cd>
<title>Red</title>
<artist>The Communards</artist>
<country>UK</country>
<company>London</company>
<price>7.80</price>
<year>1987</year>
</cd>
<cd>
<title>Unchain my heart</title>
<artist>Joe Cocker</artist>
<country>USA</country>
<company>EMI</company>
<price>8.20</price>
<year>1987</year>
</cd>
</catalog>
each time i run the program on oxygen i get a miserable format: How to adjust the output to produce a csv format?
Upvotes: 0
Views: 37
Reputation: 3247
For CSV output, you need to specify <xsl:output method="text"/>
in the XSLT. If you are looking for an output containing comma
separated values of all the child elements of <cd>
, you can use any one of the below approaches.
XSLT 1.0
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" />
<xsl:strip-space elements="*" />
<xsl:template match="cd">
<xsl:for-each select="*">
<xsl:value-of select="." />
<xsl:if test="position() != last()" >
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:if test="position() = last()" >
<xsl:text>
</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
XSLT 2.0
This version provides a more optimal solution with the additional features that it comes with.
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >
<xsl:output method="text" />
<xsl:strip-space elements="*" />
<xsl:template match="cd">
<xsl:value-of select="*" separator=", " />
<xsl:text>
</xsl:text>
</xsl:template>
</xsl:stylesheet>
Output
Red, The Communards, UK, London, 7.80, 1987
Unchain my heart, Joe Cocker, USA, EMI, 8.20, 1987
Upvotes: 1