It requires tabular data and assumes the first line of the
CSV stream is the list of field names. This should get
you going.
Here's how you'd call it.
StreamReader sr = new StreamReader( "test.csv" );
CsvToXml c = new CsvToXml( sr, Console.Out );
....
class CsvToXml
{
public CsvToXml ( TextReader csvIn, TextWriter xmlOut)
{
string ln;
bool bHeader = true;
string[] aFields = new string[] { }, aData;
while (null != (ln = csvIn.ReadLine()))
{
if (ln.Trim().Length < 1) continue; // handle empty
lines
if (bHeader)
{
bHeader = false;
aFields = this.splitLine( ln );
for (int i = 0; i < aFields.Length; i++)
{
if (Regex.Replace( aFields[i],
"[A-Za-z]([A-Za-z0-9._] | '-')*",
"" ).Length > 0)
throw new ApplicationException(
"Field cannot be converted to an NCNAME - "
+ aFields[i] );
aFields[i] = aFields[i].Replace( " ", "_" );
}
xmlOut.WriteLine( "<data>" );
}
else
{
aData = this.splitLine( ln );
if (aData.Length != aFields.Length) throw new
ApplicationException( "Invalid data encountered -
expected "+ aFields.Length.ToString() + " fields: "+ ln );
xmlOut.WriteLine( this.mergeFieldValues( aFields,
aData ) );
}
}
xmlOut.WriteLine( "</data>" );
}
private string[] splitLine( string line )
{
string[] a = line.Split( new Char[] {','} );
for (int i = 0; i < a.Length; i++)
a[i] = Regex.Replace( a[i], "(^['\"])|(['\"]
$)", "" ); // remove any enclosing quotes
return a;
}
private string mergeFieldValues( string[] fields, string
[] values )
{
StringBuilder sb = new StringBuilder( fields.ToString
().Length );
for (int i = 0; i < fields.Length; i++)
{
sb.Append( " " + fields[i] + "=\""+
values[i].Replace( "\"", """ ).Replace
( "<", "<" ).Replace( ">", ">" ) + "\"" );
}
sb.Append( "/>" );
sb.Insert( 0, "<row" );
return sb.ToString();
}
}
-----Original Message-----
I need to convert CSV (comma delimited files) to XML on
the fly for FTP. I only found references to XML / Pearl,
and I would like to find out references compatible with
microsoft... I appreciate any leads :) thanks.
.