How to create xml from Collection using Linq

How to create xml from Collection using Linq

In this post, I am going to show you how to create XML from the 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;

    }
}
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post