I need some assistance converting an xml document to a CSV file using an xslt stylesheet. I am trying to use the following xsl and I can't seem to get it right. I want my comma delimited file to include column headings, followed by the data. My biggest issues are removing the final comma after the last item and inserting a carriage return so each group of data appears on a separate line. I have been using XML Notepad.
<xsl:template match="/">
<xsl:element name="table">
<xsl:apply-templates select="/*/*[1]" mode="header" />
<xsl:apply-templates select="/*/*" mode="row" />
</xsl:element>
</xsl:template>
<xsl:template match="*" mode="header">
<xsl:element name="tr">
<xsl:apply-templates select="./*" mode="column" />
</xsl:element>
</xsl:template>
<xsl:template match="*" mode="row">
<xsl:element name="tr">
<xsl:apply-templates select="./*" mode="node" />
</xsl:element>
</xsl:template>
<xsl:template match="*" mode="column">
<xsl:element name="th">
<xsl:value-of select="translate(name(.),'qwertyuiopasdfghjklzxcvbnm_','QWERTYUIOPASDFGHJKLZXCVBNM ')" />
</xsl:element>,
</xsl:template>
<xsl:template match="*" mode="node">
<xsl:element name="td">
<xsl:value-of select="." />
</xsl:element>,
</xsl:template>
I was using the "more thorough transform" of the xslt from @flynn1179 's answer.. but found that it was taking an extraordinary amount of time when the number of rows increased. (this is using oracle dbms_xmlgen xslt transform )
I found that because I know what my 2 levels of data are called (ROWSET and ROW in this case) i was able to optimize the xslt and gain a significant performance increase.
My modified version (specifically aimed at oracle's dbms_xmlgen package) is below. it also includes bits from other csv transforms I found around the internet.
I use this to simple XSLT to convert XML to CSV; it assumes all child nodes of the root node are to be rows in the CSV, taking the element names of the first child of the root to be field names.
So this XML:
Converts to:
Not sure if this helps though, it depends how your XML is laid out.
Edit: Here's a more thorough transform:
This one will create a column in your CSV for all tag names that exist in all 'rows', and populate the appropriate column in each row.