Using Xalan Java 2.7.1, I am trying to convert a string in a simple xml to a 
csv file. Since the string in the input xml has commas, my xslt has logic to 
enclose the entire string in quotes. But the string also has quotes which 
interfere with these - so I am trying to escape those as well into a CSV 
acceptable form i.e. by replacing a double quote with 2 double quotes. For that 
I am using the recursive logic that Jeni Tennison provided in one of the group 
posts. But still the xslt does not work.

The xml is:

<?xml version="1.0" encoding="UTF-8"?>
<ColumnRow>
<ColumnDetail>String that has quotes "sdcbscbdscbsdchjbcdshc" and commas 
'Europe, Middle East &amp; Africa' ;</ColumnDetail>
</ColumnRow>

The xsl is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; 
xmlns:fo="http://www.w3.org/1999/XSL/Format";>
<xsl:output method="text" encoding="ISO-8859-1"/>
<xsl:strip-space elements="*"/>
<xsl:variable name="quot"><xsl:text>"</xsl:text></xsl:variable>

<xsl:template match="ColumnRow">
        <xsl:text>,</xsl:text><xsl:apply-templates 
select="ColumnDetail"/><xsl:text>&#10;</xsl:text>
</xsl:template>

<xsl:template match="ColumnDetail">
        <xsl:apply-templates select="EscapeQuotes"/>
        <xsl:variable name="noReturns" select="translate(.,'&#xA;&#xD;','')"/>
        <xsl:choose>
                <xsl:when test="contains($noReturns,',')">
                        <xsl:text>"</xsl:text><xsl:value-of 
select="$noReturns"/><xsl:text>"</xsl:text>
                </xsl:when>
                <xsl:otherwise>
                        <xsl:value-of select="$noReturns"/>
                </xsl:otherwise>
        </xsl:choose>
        <xsl:if test="position()!=last()">,</xsl:if>
</xsl:template>

<xsl:template name="EscapeQuotes">
        <xsl:param name="string" />
        <xsl:choose>
                <xsl:when test='contains($string,$quot)'>
                        <xsl:value-of select='substring-before($string, $quot)' 
/>
                        <xsl:text>""</xsl:text>
                        <xsl:call-template name="EscapeQuotes">
                                <xsl:with-param name="string" 
select='substring-after($string, $quot)' />
                        </xsl:call-template>
                </xsl:when>
                <xsl:otherwise>
                        <xsl:value-of select="$string" />
                </xsl:otherwise>
        </xsl:choose>
</xsl:template>

</xsl:stylesheet>


The CSV string output I get is:

,"String that has quotes "sdcbscbdscbsdchjbcdshc" and commas 'Europe, Middle 
East & Africa' ;"


Any ideas why the EscapeQuotes logic does not work?


Reply via email to