Menu ▼

Previous Next

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"))



Output :

<?xml version="1.0" encoding="utf-8"?>


  <Employee EmployeeID="EMP1002" Salary="35000">




  <Employee EmployeeID="EMP1001" Salary="25000">






Previous Next