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 25, 2016

here is the sample file.


xyz
rome


wxyz
rome2.

i am not able to see the xmltags in the clipboard after posting. but you got the requirement right?
Parent node will be and based on department, one employee will have child nodes say name, city, address etc.
then another node will be displayed for another employee who belongs to a different department.

thanks in advance.

@rpatt
Copy link

rpatt commented Nov 25, 2016

Hi,

could you please provide some input on this. if you want i can send you the sample file.

@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