LINQ to XML Tutorial
Lesson 6 of 8 · Part 6 Transforming XML to HTML table using LINQ to XML · Database
Part 6 Transforming XML to HTML table using LINQ to XML
In Part 5 of LINQ to XML tutorial, we discussed, how to tranform XML to CSV.
In this video, we will discuss transforming XML to HTML table.
Text version of the video
http://csharp-video-tutorials.blogspot.com/2014/08/part-6-transforming-xml-to-html-table.html
Slides
http://csharp-video-tutorials.blogspot.com/2014/08/part-6-transforming-xml-to-html-table_31.html
LINQ to SQL Tutorial – All Text Articles & Slides
http://csharp-video-tutorials.blogspot.com/2014/08/linq-to-xml-tutorial.html
LINQ to XML Tutorial Playlist
Dot Net, SQL, Angular, JavaScript, jQuery and Bootstrap complete courses
https://www.youtube.com/user/kudvenkat/playlists?view=1&sort=dd
We want to tranform the following XML to HTML
[?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 HTML file should look as shown below.
[table border=”1″]
[thead]
[tr]
[th]Country[/th]
[th]Name[/th]
[th]Gender[/th]
[th]TotalMarks[/th]
[/tr]
[/thead]
[tbody]
[tr]
[td]USA[/td]
[td]Mark[/td]
[td]Male[/td]
[td]800[/td]
[/tr]
[tr]
[td]USA[/td]
[td]Rosy[/td]
[td]Female[/td]
[td]900[/td]
[/tr]
[tr]
[td]India[/td]
[td]Pam[/td]
[td]Female[/td]
[td]850[/td]
[/tr]
[tr]
[td]India[/td]
[td]John[/td]
[td]Male[/td]
[td]950[/td]
[/tr]
[/tbody]
[/table]
Code to transform XML to HTML
XDocument xmlDocument = XDocument.Load(@”C:DemoDemoData.xml”);
XDocument result = new XDocument
(new XElement(“table”, new XAttribute(“border”, 1),
new XElement(“thead”,
new XElement(“tr”,
new XElement(“th”, “Country”),
new XElement(“th”, “Name”),
new XElement(“th”, “Gender”),
new XElement(“th”, “TotalMarks”))),
new XElement(“tbody”,
from student in xmlDocument.Descendants(“Student”)
select new XElement(“tr”,
new XElement(“td”, student.Attribute(“Country”).Value),
new XElement(“td”, student.Element(“Name”).Value),
new XElement(“td”, student.Element(“Gender”).Value),
new XElement(“td”, student.Element(“TotalMarks”).Value)))));
result.Save(@”C:DemoDemoResult.htm”);