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:
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
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
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
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn