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"?>
  <Student Country="USA">
  <Student Country="USA">
  <Student Country="India">
  <Student Country="India">

After transformation, data in the CSV file should look as shown below.

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

         .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");

LINQ to XML tutorial

1 comment:

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


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