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.
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
LINQ to XML tutorial
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.
<?xmlversion="1.0"encoding="utf-8"?>
<Students>
<StudentCountry="USA">
<Name>Mark</Name>
<Gender>Male</Gender>
<TotalMarks>800</TotalMarks>
</Student>
<StudentCountry="USA">
<Name>Rosy</Name>
<Gender>Female</Gender>
<TotalMarks>900</TotalMarks>
</Student>
<StudentCountry="India">
<Name>Pam</Name>
<Gender>Female</Gender>
<TotalMarks>850</TotalMarks>
</Student>
<StudentCountry="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:
Thanks for the post though, can you also help how to add header of each column ?
Reply DeleteIt would be great if you can help share these free resources
[フレーム]