Friday, 22 March 2013

convert list to xml asp.net C# using LINQ

convert list to xml asp.net C# using LINQ


This example explains how to convert list type to XML using LINQ .

Create a class called Student


    class Student
    {
        public String Name, Grade;
        public int year;
    }

Add List items of type Student


            List<Student> stuList = new List<Student>();
            stuList.Add(new Student { Name="Shyam", Grade="A",year=1990 });
            stuList.Add(new Student { Name = "Raghu", Grade = "B", year = 2010 });
            stuList.Add(new Student { Name = "Paul", Grade = "C", year = 2001 });
            stuList.Add(new Student { Name = "murthy", Grade = "D", year = 2010 });
            stuList.Add(new Student { Name = "madam", Grade = "E", year = 2000 });

Create XML from List


            XElement root = new XElement("root");

            for (int i = 0; i < stuList.Count; i++)
            {
                XElement ele = new XElement("Student", new XElement("Name", stuList[i].Name),
                                                        new XElement("Grade", stuList[i].Grade),
                                                        new XElement("Year", stuList[i].year));
                root.Add(ele);
            }
            Console.WriteLine(root);

OUTPUT:
<root>
  <Student>
    <Name>Shyam</Name>
    <Grade>A</Grade>
    <Year>1990</Year>
  </Student>
  <Student>
    <Name>Raghu</Name>
    <Grade>B</Grade>
    <Year>2010</Year>
  </Student>
  <Student>
    <Name>Paul</Name>
    <Grade>C</Grade>
    <Year>2001</Year>
  </Student>
  <Student>
    <Name>murthy</Name>
    <Grade>D</Grade>
    <Year>2010</Year>
  </Student>
  <Student>
    <Name>madam</Name>
    <Grade>E</Grade>
    <Year>2000</Year>
  </Student>
</root>

Tags:convert list to xml asp.net C# using LINQ,convert list to xml asp.ne,convert list to xml C#,LINQ to XML XElement usage.