Parsing CSV data into XML

G

Guest

Hello there,

I have a function to parse csv data and then create an xml file out of it.
Here's my function

private string delimtedDataSet( string strDelimiter,string strpath,string
outpath)
{
DataSet oDs = new DataSet();
DataTable oTable = new DataTable();
DataRow oRows;
int intCtr=0;
int Ctr=0;

oDs.DataSetName = "TEST";
oDs.Tables.Add("TABLE1");

StreamReader oSr = new StreamReader(strpath);
//go top of the file
oSr.BaseStream.Seek(0,SeekOrigin.Begin);
//add in header columns
foreach (string strFields in
oSr.ReadLine().Split(strDelimiter.ToCharArray()))
{
oDs.Tables[0].Columns.Add(strFields);
}

//add the rows

oTable = oDs.Tables[0];
try
{

while (oSr.Peek()> -1)
{
oRows = oTable.NewRow();

foreach (string strFields in
oSr.ReadLine().Split(strDelimiter.ToCharArray()))
{

oRows[intCtr] = strFields;
intCtr++;

}
intCtr = 0;
oTable.Rows.Add(oRows);
Ctr++;


}
}
catch (Exception e)
{
Response.Write("Ctr -> " + Ctr);
Response.Write(e.Message.ToString());
}
//write xml file
oDs.WriteXml(outpath);
//return xml string
return oDs.GetXml();

}

It works just fine if you don't have bad data. But some times the csv file
contains some data with ",". i.e suppose name field contains a name "John
Doe, Jr" . My code breaks in this situation. How do i fix this?

Many thanks for all your input.
 
P

Peter Bromberg [C# MVP]

Abi,
Chris Lovett of Microsoft wrote a very nice XMLCSVreader class that you can
probably find at the gotdotnet.com user samples area.
I'd recommend reviewing his excellent code to see how he handles these
issues.
My philosophy: don't reinvent the wheel. Cheers.
--Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top