This blog explains
- How read the XMl File
- How to convert an xml data as html table.
To demonstrate the above, i am using the following Xml script which contains employee Department, Name, Gender, Salary tags.
- <?xml version="1.0" encoding="utf-8" standalone="yes"?>
- <Employees>
- <Employee Department = "IT">
- <Name>Jaipal</Name>
- <Gender>Male</Gender>
- <Salary>18000</Salary>
- </Employee>
- <Employee Department = "Accounts">
- <Name>Jayanth</Name>
- <Gender>Male</Gender>
- <Salary>12000</Salary>
- </Employee>
- <Employee Department = "HR">
- <Name>Tejaswini</Name>
- <Gender>Female</Gender>
- <Salary>15000</Salary>
- </Employee>
- </Employees>
After converting the above XML file it should looks as follows.
- <table border="1">
- <thead>
- <tr>
- <th>Department</th>
- <th>Name</th>
- <th>Gender</th>
- <th>Salary</th>
- </tr>
- </thead>
- <tbody>
- <tr>
- <td>IT</td>
- <td>Jaipal</td>
- <td>Male</td>
- <td>18000</td>
- </tr>
- <tr>
- <td> Accounts </td>
- <td>Jayanth</td>
- <td>Male</td>
- <td>12000</td>
- </tr>
- <tr>
- <td>HR</td>
- <td>Tejaswini</td>
- <td>Female</td>
- <td>15000</td>
- </tr>
- </tbody>
- </table>
Steps: To transform an Xml to HTML table
The html table contains <table>, <thead>, <th>, <tbody>, <tr>, <td> and </table>, </thead>, </th>, </tbody>, </tr>, </td> tags.
- Read the XML file.
XDocument xmlDocument = XDocument.Load(@"D:\Jaipal Reddy\Expert-Exchange\LinqToXML\XmlData.xml");
- Add table as a root element, if you want to add border attribute just use XAttribute.
- Add thead, tbody as child elements to the table element.
- Add tr as child element to the thead and set the column names by adding th as child element to the tr.
- Same way add tr as child element to the tbody , and next read and populate Xml data with td.
Here is the Complete Code .
- static void Main(string[] args)
- {
- XDocument xmlDocument = XDocument.Load(@"D:\Jaipal Reddy\Expert-Exchange\LinqToXML\XmlData.xml");
-
- XDocument result = new XDocument
- (new XElement("table", new XAttribute("border", 1),
- new XElement("thead",
- new XElement("tr",
- new XElement("th", "Id"),
- new XElement("th", "Name"),
- new XElement("th", "Gender"),
- new XElement("th", "Salary"))),
- new XElement("tbody",
- from emp in xmlDocument.Descendants("Employee")
- select new XElement("tr",
- new XElement("td", emp.Attribute("Id").Value),
- new XElement("td", emp.Element("Name").Value),
- new XElement("td", emp.Element("Gender").Value),
- new XElement("td", emp.Element("Salary").Value)))));
-
- result.Save(@"D:\Jaipal Reddy\Expert-Exchange\LinqToXML\HtmlResult.htm");
- }
I hope you enjoyed it. Please provide your valuable suggestions and feedback.