Creating Sample XML using LINQ

In LINQ to XML we have XElement and XAttribute object constructors to create XML Document. XElement will be used to create Element and XAttribute will be used to add attribute(s) to the element.

Let us consider an example to create a XML which contians the Employee details.
The example contains Employees as root element, Employee as sub element. The employee details like EmployeeID, Salary as Attributes, and Department, Date of Joining(DOJ) as sub element to Employee element.

Employees Details:

Employee details

LINQ code:

new XElement("Employees", from emp in dt.AsEnumerable() orderby emp.Field<decimal>("Salary") descending select new XElement("Employee", new XAttribute("EmployeeID", emp.Field<string>("EmployeeID")), new XAttribute("Salary", emp.Field<decimal>("Salary")), new XElement("Department", emp.Field<string>("Department")), new XElement("DOJ", emp.Field<DateTime>("DOJ").ToString("MM/dd/yyyy")) )).Save(("D:\\linqxml.xml"));

Output :

<?xml version="1.0" encoding="utf-8"?> Development 06/15/2010 Development 10/03/2010