XmlCsvReader Implementation


Chris Lovett
Software Architect, WebData team, Microsoft Corporation

March 2002 (Revised February 2004)

Summary: XmlCsvReader is a sample implementation of an XmlReader that parses tab-delimited .csv files and presents their contents as a stream of XML elements; XmlReader is the Microsoft .NET Framework base class for all managed stream-level XML processing.

Download XmlCsvReaderZip.exe.

Command Line Usage

A command line .exe wrapper is provided for your convenience, or you can code directly to the XmlCsvReader class (the source code included in the above .zip file). The command line looks like this:

XmlCsvReader [-a] [-c] [-root name] [-row name] [customer.csv] 

Table 1. Options:

-a Specifies that you want attributes instead of sub-elements.
-c Specifies that the first row contains column names. Without this the columns are named "a1,a2,…an".
-root name Specifies the root element name (default is 'root').
-row name Specifies the row element name (default is 'row').
customer.csv The first file name specifies the .csv input file. If no file names are specified, then it reads from standard input
result.xml The second file name specifies the output xml file. If no second file name is specified, then it writes to standard output

XmlCsvReader Constructor

XmlCsvReader is a subclass of XmlReader so you can use it anywhere you can use the XmlReader, for example in loading XmlDocument objects. The only thing you need to understand beyond the XmlReader API itself (which is documented in the Microsoft .NET Frameworks SDK) are the XmlCsvReader constructors as follows:

public XmlCsvReader( Uri location,
                     XmlNameTable nametable)
public XmlCsvReader( Stream input,
                     Uri baseUri,
                     XmlNameTable nametable)
public XmlCsvReader( TextReader input,
                     Uri baseUri,
                     XmlNameTable nametable)
  • Uri location
    The location of the .csv file. It uses the XmlUrlResolver to resolve this so it could be a file or http location.
  • Stream input
    Alternatively you can load the reader from a stream.
  • TextReader input
    Alternatively you can load the reader from a text reader.
  • Uri baseUri
    When loading from a stream, you also need to provide the baseUri used for resolving external entities.
  • XmlNameTable nametable
    To use while atomizing element names.

XmlCsvReader Code Sample

using System.Xml; 
using Microsoft.Xml;

public class Test {
      public static void Main(){
   XmlDocument doc = new XmlDocument(); 
   XmlCsvReader reader = new XmlCsvReader(new Uri("file:///C:/My%20Download%20Files/XmlCsvReader/XmlCsvReader/input.csv"), doc.NameTable); 
   reader.FirstRowHasColumnNames = true; 
   reader.RootName = "customers"; 
   reader.RowName  = "customer";