Skip to content

Instantly share code, notes, and snippets.

@dgroft
Last active December 3, 2020 14:46
Show Gist options
  • Save dgroft/5723743 to your computer and use it in GitHub Desktop.
Save dgroft/5723743 to your computer and use it in GitHub Desktop.
Convert CSV to XML in C#
string csvPath = "...";
string xmlPath = "...";
using (StreamReader streamReader = new StreamReader(new FileStream(csvPath, FileMode.Open)))
{
// snag headers
string[] headers = streamReader.ReadLine().Split(',');
// col0="{0}" col1="{1}" coln="{n}"
string attributesFormat = string.Join(" ", headers.Select((colStr, colIdx) => string.Format("{0}=\"{{{1}}}\"", colStr, colIdx)));
// "<row ... />"
string rowFormat = string.Format("<row {0}/>", attributesFormat);
using (StreamWriter streamWriter = new StreamWriter(new FileStream(xmlPath, FileMode.Create)))
{
streamWriter.WriteLine("<root>");
string line;
while ((line = streamReader.ReadLine()) != null)
{
streamWriter.WriteLine(string.Format(rowFormat, line.Split(',')));
}
streamWriter.WriteLine("</root>");
}
}
@rpatt
Copy link

rpatt commented Nov 26, 2016

Hi,

Did you get a chance to look into thi?. Are you able to transform the required output? The output should be in parent child node format. e.g. one employee has his details based on the department and then another employee will have his details. something like that..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment