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 partialclass WebForm1: System.Web.UI.Page
{
protected void Page_Load(objectsender, EventArgs e)
{
XDocumentdoc = new XDocument(
newXDeclaration("1.0", "utf-8", "yes"), // this is xml declaration tag
newXComment("This is comment using XComment"), // this is comment
newXElement("EmployeeList", // create root element
newXElement("Employee", new XAttribute("Id", 1001), // create first child element with attribute inside root element
newXElement("Name", "Rahul"), // create another element inside first child element
newXElement("Gender", "Male"),
newXElement("Salary", "10000")),
newXElement("Employee", new XAttribute("Id", 1002), // create second child element with attribute inside root element
newXElement("Name", "Sumit"),
newXElement("Gender", "Male"),
newXElement("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.