Skip to main content

How to create xml from Collection using Linq

In this post i am going to show you how to create xml from database(for demo purpose i have created a List of person).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Linq2XML
{
 public class Program
 {
     static void Main(string[] args)
     {
         var xml = new XDocument(new XComment("Your Comment"), new XElement("Persons",
                   from c in new Person().GetList()
                   where c.FirstName.StartsWith("B")
                   select new XElement("Person",
                             new XAttribute("FirstName", c.FirstName),
                             new XAttribute("LastName", c.LastName))));

         Console.WriteLine(xml);
         Console.ReadLine();



     }
 }
 public class Person
 {
     public int ID { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public List<Person> GetList()
     {
         List<Person> list = new List<Person>()

         {
             new Person(){ID=1,FirstName="John",LastName="John"},
             new Person(){ID=2,FirstName="Bill",LastName="Gates"},
             new Person(){ID=3,FirstName="Barak",LastName="Obama"}


         };


         return list;

     }
 }
}

Comments

Post a Comment

Popular posts from this blog