Posts Tagged ‘XML’
This post will show you how to convert an XML file to CSV using Linq to XML and Anonymous types of C# 3.0. LINQ to XML is an lightweight in-memory XML programming API by which a user can manipulate the XML data such as
- Reading from XML file
- Writing to XML file
- Add or Remove XML elements from XML tree.
Now lets dig into the code sample.
Following is the code snippet which helps in converting the XML file into CSV Format.
// Loading from a file, you can also load from a stream XDocument loaded = XDocument.Load(@"C:\Contacts.xml"); // create a writer and open the file TextWriter tw = new StreamWriter("c:\\XmltoCSV.txt"); // Query the data and write out a subset of contacts var contacts = from c in loaded.Descendants("CONTACT") select new { FirstName = (string)c.Element("FIRSTNAME"), LastName = (string)c.Element("LASTNAME"), City = (string)c.Element("CITY"), State = (string)c.Element("STATE"), Country = (string)c.Element("COUNTRY") }; foreach (var contact in contacts) { string s = contact.FirstName + "," + contact.LastName+ "," + contact.City+ "," + contact.State + "," + contact.Country; // write a line of text to the file tw.WriteLine(s); } // close the stream tw.Close();
INPUT (XML File): We will use the XML file to read the data.
<?xml version='1.0' encoding='utf-8'?> <CONTACTS> <CONTACT> <FIRSTNAME>John</FIRSTNAME> <LASTNAME>Doe</LASTNAME> <CITY>Miami</CITY> <STATE>Florida</STATE> <COUNTRY>USA</COUNTRY> </CONTACT> <CONTACT> <FIRSTNAME>Shane</FIRSTNAME> <LASTNAME>Warne</LASTNAME> <CITY>Sydney</CITY> <STATE>New South Wales</STATE> <COUNTRY>Australia</COUNTRY> </CONTACT> <CONTACT> <FIRSTNAME>Adam</FIRSTNAME> <LASTNAME>Smith</LASTNAME> <CITY>London</CITY> <STATE>London</STATE> <COUNTRY>UK</COUNTRY> </CONTACT> </CONTACTS>
OUTPUT (CSV file): Comma Separated File (CSV) will be generated as the output.
John,Doe,Miami,Florida,USA Shane,Warne,Sydney,New South Wales,Australia Adam,Smith,London,London,UK
Tags: C#, Linq to XML, XML, XmltoCSV
