Create the XML document using LINQ to XML in C#

XML document is widely used file in the projects where we can store the small or big data such as configuration settings or last used data on the form. .Net framework provides various way to create the XML files (such as DataSet.WriteXML), but my concern it is so easy to create the XML document by using the LINQ to XML. I will explain you about to create the XML file using LINQ to XML.

We use the xDocument class of the System.Xml.Linq namespace, this class is inherit by XContainer class.
We just need to create the instance of this class with the specified System.Xml.Linq.XDeclaration and content. So We can define this constructor of the xDocument in this way:

public XDocument(XDeclaration _declaration, params object[] _content);

Where _declaration is the XML declaration for the document and _content is the body of the document.

Now We assume that we need to create the following xml(Figure 1). The Figure 2 show the XML Tree of the document

Figure 1: XML document for employee’s salary

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

Figure : XML tree for employee’s salary
Salary xml tree

For it the code will be:

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

The above code shows the creation of a document that contains the 4 employee node with name and salary.