Create a xml file using LINQ:

Sksingh
Posted by Sksingh under LINQ category on | Points: 40 | Views : 2616
Using the classes from the System.Xml.Linq namespace and the features available in .NET 3.5, constructing an XML document is very easy and very readable.

Constructing a document in this way is possible because of the functional construction feature in LINQ to XML. Functional construction is simply a means of creating an entire document tree in a single statement.

namespace LINQContext
{
class Program
{
static void Main(string[] args)
{
var data = getDataSource().ToArray();
XElement element = new XElement("Employees", from emp in data select
new XElement("Employee",
new XElement("EmpID",emp.EmpNo),
new XElement("EmpName",emp.EmpName),
new XElement("Address",emp.EmpAddress)));
element.Save("Data.xml");
Console.WriteLine(element);
Console.ReadLine();
}

public static List<Emp> getDataSource()
{
List<Emp> collection = new List<Emp>();
collection.Add(new Emp { EmpNo = 123, EmpName = "Sunil",
EmpAddress = "Delhi" });
collection.Add(new Emp { EmpNo = 124, EmpName = "syam", EmpAddress = " Delhi " });
collection.Add(new Emp { EmpNo = 125, EmpName = "ranjit", EmpAddress = " Delhi " });
collection.Add(new Emp { EmpNo = 126, EmpName = "anil", EmpAddress = " Delhi " });
collection.Add(new Emp { EmpNo = 127, EmpName = "jiju", EmpAddress = " Delhi " });
collection.Add(new Emp { EmpNo = 128, EmpName = "anil", EmpAddress = " Delhi " });
collection.Add(new Emp { EmpNo = 129, EmpName = "syam", EmpAddress = " Delhi " });
collection.Add(new Emp { EmpNo = 130, EmpName = "ranjit", EmpAddress = " Delhi " });
return collection;

}
}
partial class Emp
{
public int EmpNo
{
get;set;
}
public string EmpName
{
get;set;
}
public string EmpAddress
{
get;set;
}

}

}

Comments or Responses

Posted by: Susanthampy on: 6/8/2011 Level:Bronze | Status: [Member] [MVP] | Points: 10
nice
Posted by: Jayeshl on: 6/9/2011 Level:Starter | Status: [Member] | Points: 10
Posted by: Santosh4u on: 6/13/2011 Level:Bronze | Status: [Member] | Points: 10
hi Sksingh
it's very nice code ..
can u plz send me some code and examples on linq to my mail id(santosh.online4uu@gmail.com)

Regards
santosh
http://santoshdotnetarena.blogspot.com/
Posted by: Sksingh on: 6/13/2011 Level:Starter | Status: [Member] | Points: 10
Hi Santosh,

Are you looking for basic LINQ example , I mean LINQ TO SQL or LINQ To XML or LINQ To object.

Sure i will send you all d codes related to LINQ.
Posted by: Santosh4u on: 6/22/2011 Level:Bronze | Status: [Member] | Points: 10
many many thanx Sksingh
plz send me as soon as possible becaz i m going to work on that....

thanx and regards
santosh
Posted by: Deveder on: 7/8/2011 Level:Starter | Status: [Member] | Points: 10
HI sunil singh,

Its Really use full who are working with xml . Gud one .
Posted by: Lakn2 on: 7/12/2011 Level:Starter | Status: [Member] | Points: 10
good one

Login to post response