Tuesday, May 12, 2009

Made XML file from object collection witrh LINQ

Hi,

Last time i seem in the forum, he ask a question how to make XML file from the object collection or array with LINQ.Because of LINQ has a excellent support to XML.

Here Code snippet.

To this i just take simple example.

C#.NET


Private void MakeXMlFile()
{

Employee[] employees = new[] {
new Employee {FirstName = "Joe", LastName = "Rattz", Email="Test@hotmail.com",Phone="12345343"
},
new Employee {FirstName = "Ewan", LastName = "Buckingham",
Email="Test2@hotmail.com",Phone="122232345343"}};

XElement xBookParticipants =
new XElement("Employees",
employees.Select(p =>
new XElement("Employee",
new XElement("FirstName", p.FirstName),
new XElement("LastName", p.LastName),new XElement("Email",p.Email),
new XElement("Phone",p.Phone))));
Console.WriteLine(employees);

}


VB.NET

Class Employee
Public FirstName As String
Public LastName As String
Public Email As String
Public Phone As String
End Class


private sub MakeXML()

Dim employees As Employee() = New () {New Employee(), New Employee()}

Dim xBookParticipants As New XElement("Employees", employees.[Select](Function(p) New XElement("Employee", New XElement("FirstName", p.FirstName), New XElement("LastName", p.LastName), New XElement("Email", p.Email), New XElement("Phone", p.Phone))))
Console.WriteLine(employees)
Console.ReadLine()
End Sub

Keep It Watch
Thank you

No comments:

Post a Comment