Re: [xsl] CSV to XML

Subject: Re: [xsl] CSV to XML
From: James Neff <jneff@xxxxxxxxxxxxxxxx>
Date: Fri, 09 Sep 2005 09:47:22 -0400
This is an XSLT 2.0 solution:

The way I did this was using a parameter for the stylesheet.  This
parameter contains the filename of your CSV file.  I also call the
template "main" but I'm sure there is a different way to kick this off
if you don't like to call templates from the command line.


<xsl:transform
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
   version="2.0"
   xmlns:xs="http://www.w3.org/2001/XMLSchema";
   exclude-result-prefixes="xs">
  
   <xsl:output method="xml" indent="yes"/>
  
   <xsl:strip-space elements="*"/>

   <xsl:param name="input" as="xs:string" required="yes"/>

   <!-- Read the input file into a string variable -->

   <xsl:variable name="input-text" as="xs:string"
select="unparsed-text($input, 'UTF-8')"/>
  
   <!-- Split the input file into a sequence of strings, each holding
one line of the input -->
   <xsl:variable name="lines" as="xs:string*"
select="tokenize($input-text, '\n')"/>

<xsl:variable name="parsed-lines">
       
        <xsl:element name="root">
   
            <xsl:for-each select="$lines">

             <xsl:element name="row">

                   <xsl:for-each select="tokenize(.,',')">

                      <xsl:element name="field">

                         <xsl:value-of select="." />

                      </xsl:element>

                   </xsl:for-each>

             </xsl:element>

       </xsl:element>

</xsl:variable>

    <xsl:template name="main">
   
        <xsl:element name="file_header">
           
            <xsl:copy-of select="$parsed-lines" />
    
        </xsl:element>
       
    </xsl:template>

</xsl:transform>

Arthur Maloney wrote:

>Hello xsl-list,
>
>
>   Prior to transform, I would like to convert some CSV files to XML
>
>  e.g.
>  row 1: fieldName1,fieldName2,fieldName3,...
>  ...
>  row n: fred,67.8,I love XSLT2.0,...
>
>  does anybody have any example code for converting to an XML file
>
>  e.g or as attributes
>  <CsvFileName>
>     <fieldName1>...</fieldName1>
>     ...
>  </CsvFileName>
>  
>  Ideally C# but Java will do.

Current Thread