Last active
December 3, 2020 14:46
-
-
Save dgroft/5723743 to your computer and use it in GitHub Desktop.
Convert CSV to XML in C#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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..