Create XML document in C# using LINQ XDocument Class

In this articles, I am going to explain you how to create XML document in C# using LINQ XDocument class. Below is step by step tutorial.

Namespace Required

Create an empty asp.net web application and add a webform to it.
Include below namespace.

using System.Xml.Linq;

C# Code

Below is the code for simple XML document generation using LINQ class in C#.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Linq;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        XDocument doc = new XDocument(
            new XDeclaration("1.0", "utf-8", "yes"),  // this is xml declaration tag
            new XComment("This is comment using XComment"), // this is comment
            new XElement("EmployeeList",         // create root element

                new XElement("Employee", new XAttribute("Id", 1001), // create first child element with attribute inside root element
                new XElement("Name", "Rahul"), // create another element inside first child element
                new XElement("Gender", "Male"),
                new XElement("Salary", "10000")),

                new XElement("Employee", new XAttribute("Id", 1002), // create second child element with attribute inside root element
                new XElement("Name", "Sumit"),
                new XElement("Gender", "Male"),
                new XElement("Salary", "15000"))
                    )
            );

        // save xml document into root directory of application
        doc.Save(Server.MapPath("Employee.xml"));
    }
}
}

After executing code, a xml document will be generation and saved into root directory of application. Open document in the browser and you can see content of xml document as below.

Create XML document in C# using LINQ XDocument class


Share this

Related Posts

Previous
Next Post »