Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 5 - Transforming XML to CSV using LINQ to XML

Suggested Videos
Part 2 - Creating an XML document using in-memory collection of objects
Part 3 - Querying xml document using linq to xml
Part 4 - Modifying xml document using linq to xml



In your application there may be a need to transform an XML document into
1. CSV format
2. HTML format
3. Different XML format



In this video, we will discuss transforming the following XML document into CSV format.
<?xml version="1.0" encoding="utf-8"?>
<Students>
  <Student Country="USA">
    <Name>Mark</Name>
    <Gender>Male</Gender>
    <TotalMarks>800</TotalMarks>
  </Student>
  <Student Country="USA">
    <Name>Rosy</Name>
    <Gender>Female</Gender>
    <TotalMarks>900</TotalMarks>
  </Student>
  <Student Country="India">
    <Name>Pam</Name>
    <Gender>Female</Gender>
    <TotalMarks>850</TotalMarks>
  </Student>
  <Student Country="India">
    <Name>John</Name>
    <Gender>Male</Gender>
    <TotalMarks>950</TotalMarks>
  </Student>
</Students>

After transformation, data in the CSV file should look as shown below.
USA,Mark,Male,800
USA,Rosy,Female,900
India,Pam,Female,850
India,John,Male,950

Code to transform XML to CSV
StringBuilder sb = new StringBuilder();
string delimiter = ",";

XDocument.Load(@"C:\Demo\Demo\Data.xml").Descendants("Student")
         .ToList().ForEach(element => sb.Append(
                            element.Attribute("Country").Value + delimiter +
                            element.Element("Name").Value + delimiter +
                            element.Element("Gender").Value + delimiter +
                            element.Element("TotalMarks").Value + "\r\n"));

StreamWriter sw = new StreamWriter(@"C:\Demo\Demo\Result.csv");
sw.WriteLine(sb.ToString());
sw.Close();

LINQ to XML tutorial

1 comment:

  1. Thanks for the post though, can you also help how to add header of each column ?

    ReplyDelete

It would be great if you can help share these free resources