C# CSV to XML Conversion, CSV to XML Conversion using LINQ Read more at http://dotnetdud.blogspot.com/2008/10/c-csv-to-xml-conversion-csv-to-xml.html#Aj2tQrpD5ELjLI8Z.99
How to Convert CSV to XML using C#
Language Integrated Query (LINQ) can be used to convert a CSV file to XML. Here is the sample CSV file that needs to be converted
The following code reads the CSV file to an array. LINQ is used to loop through the array and the contents are written as XML using XElement (System.XML.Linq).
public void ConvertCSVToXML()
{
String[] FileContent = File.ReadAllLines(@"C:\Temp\vba.csv");
String XMLNS = "";
XElement Inv = new XElement("Invoice",
from items in FileContent
let fields = items.Split(',')
select new XElement("Item",
new XElement("ID", fields[0]),
new XElement("Name", fields[1]),
new XElement("Price", fields[2]),
new XElement("Availability", fields[3]),
new XElement("TotalPrice", fields[4])
)
);
File.WriteAllText(@"C:\Temp\vba.xml", XMLNS + Inv.ToString() );
}
image: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiqn6aFrvLkx9RZkbEHsX3hs5CgHHnjWd9JojseJMS3D__FqEovvcWUrqrWoYgPZ9G2ZhGPvCLhCEnQlNdcMEnP5JmAbHEW76WGqxOFDAeiHYl7Rng1mcWHzcBmOLaPmc1AsCsDQ9w6HjWm/s400/dnd_csv2xml1.JPG
The output XML looks like
image: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjN7uTFGxx0gODhtn9UqSWJluPVcbT1nrnOcodDu3WHlSd514syk_ED53V3jfAsCbCp2OFTcy9XO-mOMSY3vOjzfAjG7kDkomdkTRxSXt7z74dpzt6BJ_WWAiRCJYgq4qpGprtC3OOyIeiY/s400/dnd_csv2xml2.JPG
Read more at http://dotnetdud.blogspot.com/2008/10/c-csv-to-xml-conversion-csv-to-xml.html#Aj2tQrpD5ELjLI8Z.99
Comments
Post a Comment