DotNetCurry Logo

Convert a List<> Into XML using LINQ

Posted by: Suprotim Agarwal , on 12/8/2009, in Category LINQ
Views: 105349
Abstract: In this article, I will demonstrate a simple example of converting a List<> to XML using LINQ.
Convert a List<> Into XML using LINQ
 
In this article, I will demonstrate a simple example of converting a List<> to XML using LINQ. I assume that you are familiar with LINQ to XML. If that is not the case, I would recommend you to get some hands-on on LINQ to XML. These three articles will help out out:
Let us get started. The first step is to define a List<>. For demonstration purposes, I will create a Console Application and declare a List<> of Employees as shown below:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
 
namespace ListToXML
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Employee> empList = new List<Employee>();
            empList.Add(new Employee() { ID = 1, FName = "John", LName = "Shields", DOB = DateTime.Parse("12/11/1971"), Sex = 'M' });
            empList.Add(new Employee() { ID = 2, FName = "Mary", LName = "Jacobs", DOB = DateTime.Parse("01/17/1961"), Sex = 'F' });
            empList.Add(new Employee() { ID = 3, FName = "Amber", LName = "Agar", DOB = DateTime.Parse("12/23/1971"), Sex = 'M' });
            empList.Add(new Employee() { ID = 4, FName = "Kathy", LName = "Berry", DOB = DateTime.Parse("11/15/1976"), Sex = 'F' });
            empList.Add(new Employee() { ID = 5, FName = "Lena", LName = "Bilton", DOB = DateTime.Parse("05/11/1978"), Sex = 'F' });
            empList.Add(new Employee() { ID = 6, FName = "Susanne", LName = "Buck", DOB = DateTime.Parse("03/7/1965"), Sex = 'F' });
            empList.Add(new Employee() { ID = 7, FName = "Jim", LName = "Brown", DOB = DateTime.Parse("09/11/1972"), Sex = 'M' });
            empList.Add(new Employee() { ID = 8, FName = "Jane", LName = "Hooks", DOB = DateTime.Parse("12/11/1972"), Sex = 'F' });
            empList.Add(new Employee() { ID = 9, FName = "Robert", LName = "", DOB = DateTime.Parse("06/28/1964"), Sex = 'M' });
            empList.Add(new Employee() { ID = 10, FName = "Cindy", LName = "Fox", DOB = DateTime.Parse("01/11/1978"), Sex = 'M' });
 
        }
    }
 
    class Employee
    {
        public int ID { get; set; }
        public string FName { get; set; }
       public string LName { get; set; }
        public DateTime DOB { get; set; }
        public char Sex { get; set; }
    }
}
 
VB.NET
Option Infer On
 
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Xml.Linq
 
Module Module1
 
    Sub Main(ByVal args() As String)
        Dim empList As New List(Of Employee)()
        empList.Add(New Employee() With {.ID = 1, .FName = "John", .LName = "Shields", .DOB = Date.Parse("12/11/1971"), .Sex = "M"c})
        empList.Add(New Employee() With {.ID = 2, .FName = "Mary", .LName = "Jacobs", .DOB = Date.Parse("01/17/1961"), .Sex = "F"c})
        empList.Add(New Employee() With {.ID = 3, .FName = "Amber", .LName = "Agar", .DOB = Date.Parse("12/23/1971"), .Sex = "M"c})
        empList.Add(New Employee() With {.ID = 4, .FName = "Kathy", .LName = "Berry", .DOB = Date.Parse("11/15/1976"), .Sex = "F"c})
        empList.Add(New Employee() With {.ID = 5, .FName = "Lena", .LName = "Bilton", .DOB = Date.Parse("05/11/1978"), .Sex = "F"c})
        empList.Add(New Employee() With {.ID = 6, .FName = "Susanne", .LName = "Buck", .DOB = Date.Parse("03/7/1965"), .Sex = "F"c})
        empList.Add(New Employee() With {.ID = 7, .FName = "Jim", .LName = "Brown", .DOB = Date.Parse("09/11/1972"), .Sex = "M"c})
        empList.Add(New Employee() With {.ID = 8, .FName = "Jane", .LName = "Hooks", .DOB = Date.Parse("12/11/1972"), .Sex = "F"c})
        empList.Add(New Employee() With {.ID = 9, .FName = "Robert", .LName = "", .DOB = Date.Parse("06/28/1964"), .Sex = "M"c})
        empList.Add(New Employee() With {.ID = 10, .FName = "Cindy", .LName = "Fox", .DOB = Date.Parse("01/11/1978"), .Sex = "M"c})
  
   End Sub
End Module
 
Friend Class Employee
    Private privateID As Integer
    Public Property ID() As Integer
        Get
            Return privateID
        End Get
        Set(ByVal value As Integer)
            privateID = value
        End Set
    End Property
    Private privateFName As String
    Public Property FName() As String
        Get
            Return privateFName
        End Get
        Set(ByVal value As String)
            privateFName = value
        End Set
    End Property
    Private privateLName As String
    Public Property LName() As String
        Get
            Return privateLName
        End Get
        Set(ByVal value As String)
            privateLName = value
        End Set
    End Property
    Private privateDOB As Date
    Public Property DOB() As Date
        Get
            Return privateDOB
        End Get
       Set(ByVal value As Date)
            privateDOB = value
        End Set
    End Property
    Private privateSex As Char
    Public Property Sex() As Char
        Get
            Return privateSex
        End Get
        Set(ByVal value As Char)
            privateSex = value
        End Set
    End Property
End Class
 
The next step is to convert this List<> to XML. The root node in our XML, without a doubt, can be <Employees>. Now if you observe, the Employee ID property uniquely identifies each Employee. We can create Parent Nodes with the attribute ID and all the other properties like Fname, Lname, Dob and Age will be the Child Nodes. Here’s the LINQ query to do so:
C#
try
{
    var xEle = new XElement("Employees",
                from emp in empList
                select new XElement("Employee",
                             new XAttribute("ID", emp.ID),
                               new XElement("FName", emp.FName),
                               new XElement("LName", emp.LName),
                               new XElement("DOB", emp.DOB),
                               new XElement("Sex", emp.Sex)
                           ));
 
    xEle.Save("D:\\employees.xml");
    Console.WriteLine("Converted to XML");
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
Console.ReadLine();
VB.NET
Try
      Dim xEle = New XElement("Employees", _
             From emp In empList _
             Select New XElement("Employee", New XAttribute("ID", emp.ID), _
                    New XElement("FName", emp.FName), _
                    New XElement("LName", emp.LName), _
                    New XElement("DOB", emp.DOB), _
                   New XElement("Sex", emp.Sex)))
 
            xEle.Save("D:\employees.xml")
            Console.WriteLine("Converted to XML")
Catch ex As Exception
      Console.WriteLine(ex.Message)
End Try
Console.ReadLine()
On running the application, the output is similar to the following:
Output
I hope you liked this article and I thank you for viewing it. The entire source code of this article can be downloaded over here
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Mike on Wednesday, December 9, 2009 7:41 AM
Could you provide a Print-Friendly version?
When I click the print button, it is a NOT Print-Friendly version with too much margin in the page.
Comment posted by Carol on Thursday, December 10, 2009 4:35 AM
Thanks for your feedback. We will accomodate your suggestion in the set of next changes to the site.

Carol
Site Editor
Comment posted by David on Thursday, December 6, 2012 6:35 AM
if Employee class contains child how we can write linq query to convert to XML.
Comment posted by Dinesh Persaud on Monday, February 25, 2013 10:52 AM
i want to create an xml file in my solution and write/read and delete from it.. how do i do that?
Comment posted by dani on Thursday, August 29, 2013 7:49 AM
Excellent solution. Thank you so much
Comment posted by Balamurugan on Friday, October 31, 2014 2:41 AM
This worked out for me but the first column value is not reading. It is reading as null.
It is like
<Employees>
<Employee ID=1>
<Name=ABC>

Instead i want a structure like
<Employees>
<Employee>
    <ID=1>
    <Name=ABC>
Comment posted by dsf on Monday, January 19, 2015 5:43 AM
dfsfsdfdsfdsfds
Comment posted by Aleksey Gerasimov on Saturday, May 2, 2015 5:48 AM
Can we convert xml back to List<Employee>?
Comment posted by Praful on Saturday, May 2, 2015 8:28 PM
Aleksey he has covered almost every linq xml scenario here - http://www.dotnetcurry.com/showarticle.aspx?ID=727