Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

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

No comments:

Post a Comment

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.