Cette class permet de convertir un fichier CSV en XML de manière simple et performante.
Méthode d?appel
pathSource = @"c:\test.csv";
pathDestination = @"c:\test.xml";
ConvertCSVToXML cCSV2XML = new ConvertCSVToXML();
cCSV2XML.convert(pathSource,pathDestination);
Source / Exemple :
public class ConvertCSVToXML
{
private string _root = "CSVRoot";
private string _node = "CSVTable";
private char _separator =',';
public bool convert(string pathSource, string pathDestination)
{
StreamReader stream = null;
string[] saEntetes = null;
string sLigne = "";
DataSet csvDataSet = null;
DataTable csvDataTable= null;
try
{
csvDataSet = new DataSet(_root);
csvDataTable= new DataTable(_node);
stream = new StreamReader(pathSource, true);
sLigne = stream.ReadLine();
saEntetes = sLigne.Split(_separator);
for(int i=0;i<saEntetes.Length;i++)
{
csvDataTable.Columns.Add(saEntetes[i]);
}
sLigne = stream.ReadLine();
while( sLigne!=null )
{
csvDataTable.Rows.Add(sLigne.Split(_separator));
sLigne = stream.ReadLine();
}
csvDataSet.Tables.Add(csvDataTable);
csvDataSet.WriteXml(pathDestination);
return true;
}
catch(Exception e)
{
Console.WriteLine( e.Message );
return false;
}
finally
{
stream.Close();
if(csvDataSet!=null) csvDataSet.Dispose();
if(csvDataTable != null) csvDataTable.Dispose();
}
}
}