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>"); | |
} | |
} |
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.
Hi,
could you please provide some input on this. if you want i can send you the sample file.
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
thanks man for sharing it. now it is coming in single line.
can we add multi childnodes say based on the employee department.
something like this.
xyz
rome
...
wxyz