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;
}
}
}