Csv to xml with variable number of columns
I was asked to come up with a solution to take a .csv file to xml for data transfer from one program to another. I am running Widows 7 but when finished it will run on Server 2003 and Server 2008. I am using Saxon v9.5 for the xslt. I'm having trouble getting the file to parse.
The .csv file looks like:
AA_00002,EUTANKID2,08/20/2013,91626020,,08/20/2013,43
AA_00003,EUTANKID3,08/20/2013,91625870,,08/20/2013,88
AA_00004,EUTANKID4,08/20/2013,91626011,,08/20/2013,50
AA_00005,EUTANKID5,08/20/2013,1625911,,08/20/2013,63
AA_00006,EUTANKID6,08/20/2013,0,,08/20/2013,76
AA_00007,EUTANKID7,08/20/2013,91625890,,08/20/2013,120
I run it with the following stylesheet:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:param name="identifier"/>
<xsl:param name="uri"/>
<xsl:template match="/">
<xsl:variable name="filename" select="'file:///C:/Users/rjacobs/Desktop/DJBASIN_EUTANK_exportout.csv'"/>
<xsl:if test="unparsed-text-available($filename)">
<xsl:value-of select="unparsed-text($filename)"/>
</xsl:if> "
<xsl:variable name="CsvExport" select="unparsed-text($filename)"/>
<xsl:variable name="data">
<list>
<xsl:analyze-string select="$CsvExport" regex="\n">
<xsl:non-matching-substring>
<row>
<xsl:analyze-string select="." regex="," flags="x">
<xsl:non-matching-substring>
<col>
<xsl:value-of select="normalize-space(.)"/>
</col>
</xsl:non-matching-substring>
</xsl:analyze-string>
</row>
</xsl:non-matching-substring>
</xsl:analyze-string>
</list>
</xsl:variable>
</xsl:template>
</xsl:stylesheet>
and get this as an output:
<?xml version="1.0" encoding="UTF-8"?>AA_00002,EUTANKID2,08/20/2013,91626020,,08/20/2013,43
AA_00003,EUTANKID3,08/20/2013,91625870,,08/20/2013,88
AA_00004,EUTANKID4,08/20/2013,91626011,,08/20/2013,50
AA_00005,EUTANKID5,08/20/2013,1625911,,08/20/2013,63
AA_00006,EUTANKID6,08/20/2013,0,,08/20/2013,76
AA_00007,EUTANKID7,08/20/2013,91625890,,08/20/2013,120
Then I run a second pass with this stylesheet:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
<xsl:param name="identifier"/>
<xsl:param name="uri"/>
<xsl:variable name="data"/>
<xsl:template match="/">
<xsl:variable name="filename" select="'file:///E:/Saxon/final_test.xml'"/>
<xsl:for-each select="$filename//row">
<EUExport>
<FacId>
<EUTankId>
<xsl:value-of select="col[1]"/>
</EUTankId>
<FacilityId>
<xsl:value-of select="col[0]"/>
</FacilityId>
<Date>
<xsl:value-of select="col[5]"/>
</Date>
<TankId>
<xsl:value-of select="col[3]"/>
</TankId>
<TankLevel>
<xsl:value-of select="col[6]"/>
</TankLevel>
<TankInterface>
<xsl:text></xsl:text>
</TankInterface>
</FacId>
</EUExport>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
The output is the same as the input.
|