Search code examples
xsltxslt-2.0apache-fop

How do i log to a .txt file while processing the contents of XML using XSLT?


I am working with Apache FOP. I am using XSLT to convert XML to PDF (which works fine). I need to create a journal file (basically a .txt file). The journal file should consist of values from tag values from XML while processing it in XSLT. i require this journal file for some reconciliation. Example:

<Details>
 <Name>Pooja</Name>
 <Country>India</Country>
 <OtherInfo>ABC</OtherInfo>
</Details>

I would need the .txt contents as below:

Pooja,India,ABC

How do i achieve this?


Solution

  • There are several ways that you could generate the CSV output. If there is a chance those values could contain , then you might want to add some logic to escape or wrap with quotes. But for the simple case of joining those element values with , you could start with either of these:

    XSLT 2.0 (or greater) using xsl:value-of with @separator=",":

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
        <xsl:output method="text"/>
        <xsl:template match="Details">
            <xsl:value-of select="*" separator=","/>
        </xsl:template>
    </xsl:stylesheet>
    

    XSLT 2.0 (or greater) using fn:string-join():

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
        <xsl:output method="text"/>
        <xsl:template match="Details">
            <xsl:value-of select="string-join(*,',')"/>
        </xsl:template>
    </xsl:stylesheet>
    

    XSLT 1.0 using xsl:for-each and testing the position() to determine whether to emit the ,:

    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
        <xsl:output method="text"/>
        <xsl:template match="Details">
            <xsl:for-each select="*">
                <xsl:if test="position() > 1">,</xsl:if>
                <xsl:value-of select="."/>
            </xsl:for-each>
        </xsl:template>
    </xsl:stylesheet>