best LFS

Wednesday, 2 July 2014

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.



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



Development
06/15/2010


Development
10/03/2010



No comments:

Post a Comment