Generate xml document with elements and attributes using LINQ to XML

To generate a XML document with elements and attributes is easy by using LINQ to XML. LINQ to XML provides the XDocument, XElement and XAttribute classes,with the help of XElement class we can create XML content and create a new XML file using the XDocument class.

Assume the following xml file:

<?xml version="1.0" encoding="UTF-16"?>
<EmployeeList> 
   <Employee Salary="2300" Name="Mohan"/>
   <Employee Salary="1800" Name="John"/> 
   <Employee Salary="4200" Name="David"/>
   <Employee Salary="2300" Name="Cam R"/>
</EmployeeList>

Following code will create the above XML file that contains the elements with some attributes.

    XElement EmployeeList =
                new XElement("EmployeeList",
                    new XElement("Employee",
                        new XAttribute("Name", "Mohan"),
                        new XAttribute("Salary", "2300")),
                    new XElement("Employee",
                        new XAttribute("Name", "John"),
                        new XAttribute("Salary", "1800")),
                    new XElement("Employee",
                        new XAttribute("Name", "David"),
                        new XAttribute("Salary", "4200")),
                    new XElement("Employee",
                        new XAttribute("Name", "Cam R"),
                        new XAttribute("Salary", "2300"))
                   );
 XDocument xmlDoc = new XDocument(
        new XDeclaration("1.0", "utf-16", "true"), EmployeeList);
 xmlDoc.Save("D:\\Salary.xml");