Home > Code > LINQ > Create XML document using LINQ (Linq to Xml)

Create XML document using LINQ (Linq to Xml)

by Thamil   on May 09, 2011   Category: LINQ   |  Views: 1663    |  Points: 25   |  Gold 


We can get lot of code snippets on how to read a xml file using LINQ, but here I’m describing how to create XML file using LINQ (Linq to Xml) within a single statement, this will help when you create xml file using LINQ. Find the below sample code

Include below namespace
using System;
using System.Xml.Linq;

Create XML document by using XDocument
protected void CreatXMLDoc_Click(object sender, EventArgs e)
{
XDocument xdoc = new XDocument(
new XDeclaration("1.0", "UTF-16", "true"),
new XElement("Company",
new XElement("Employee",
new XElement("ID", "100"),
new XElement("Name", "Kenny"),
new XElement("Job", "Manager"),
new XElement("Tel", "45639877"),
new XElement("Place", "UK"),
new XElement("zip", "21321")),
new XElement("Employee",
new XElement("ID", "101"),
new XElement("Name", "Jhon"),
new XElement("Job", "Sr Manager"),
new XElement("Tel", "45639878"),
new XElement("Place", "India"),
new XElement("zip", "456321"))
));
xdoc.Save(@"d:\test.xml");
}

XDocument, which is a class used to create xml document, XDeclaration used to define the xml version and encoding details, XElement used to define xml element and value of the specific element and store the xml document using save method. Finally you will get the xml document like
<?xml version="1.0" encoding="utf-16"?>
<Company>
<Employee>
<ID>100</ID>
<Name>Kenny</Name>
<Job>Manager</Job>
<Tel>45639877</Tel>
<Place>UK</Place>
<zip>21321</zip>
</Employee>
<Employee>
<ID>101</ID>
<Name>Jhon</Name>
<Job>Sr Manager</Job>
<Tel>45639878</Tel>
<Place>India</Place>
<zip>456321</zip>
</Employee>
</Company>






Post Code  |  Code Snippet Home

User Responses


No response found, be the first to review this code snippet.

Submit feedback about this code snippet

Please sign in to post feedback

Latest Posts