Last active
March 23, 2016 10:33
-
-
Save nVlast/1798f8a1ea2d87bc882c to your computer and use it in GitHub Desktop.
Convert csv file to xml
This file contains 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
public static void ToXml(string srcFilepath, string dstFilepath, string rootNodeName, string elementNodeName) | |
{ | |
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(srcFilepath)) | |
using (XmlTextWriter writer = new XmlTextWriter(dstFilepath, Encoding.UTF8)) | |
{ | |
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; | |
parser.SetDelimiters(new string[] { "," }); | |
string[] headers = parser.ReadFields(); | |
writer.WriteStartDocument(); | |
writer.WriteWhitespace("\n"); | |
writer.WriteStartElement(rootNodeName); | |
writer.WriteWhitespace("\n"); | |
while (!parser.EndOfData) | |
{ | |
string[] row = parser.ReadFields(); | |
writer.WriteStartElement(elementNodeName); | |
writer.WriteWhitespace("\n"); | |
for (int i = 0; i < headers.Length; i++) | |
{ | |
writer.WriteElementString(headers[i], row[i]); | |
writer.WriteWhitespace("\n"); | |
} | |
writer.WriteEndElement(); | |
writer.WriteWhitespace("\n"); | |
} | |
writer.WriteEndElement(); | |
writer.WriteWhitespace("\n"); | |
writer.WriteEndDocument(); | |
writer.WriteWhitespace("\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment