Deserialize XML Document Data and Convert into .Net Array List

Category > ASP.NET || Published on : Monday, June 29, 2015 || Views: 4186 || Deserialize XML Document Data and Convert into .Net Array List Convert into .Net Array List Deserialize XML Document Data


In this tutorial, we are going to learn how to read the data from XML document or file and then deserialize into array or list object in .NET using C# with code example

Step 1: Create a simple XML file(file:- XMLFile.xml) with data we will load into list object

<?xml version="1.0" encoding="utf-8"?>
<EmployeesCollection>
  <Employees>
    <Employee>
      <Id>1</Id>
      <Name>Bill Gates</Name>
      <Department>IT</Department>
    </Employee>


    <Employee>
      <Id>2</Id>
      <Name>SteveJobs</Name>
      <Department>HR</Department>
    </Employee>

    <Employee>
      <Id>3</Id>
      <Name>Satya Nadella</Name>
      <Department>Managment</Department>
    </Employee>
    
    
  </Employees>
</EmployeesCollection>

Step 2: Create a "Employee.cs" file in App_code folder with the following codes:-

using System;
using System.Xml.Serialization;

/// <summary>
/// Summary description for Employee
/// </summary>
[Serializable()]
public class Employee
{
    [XmlElement("Id")]
    public int Id { get; set; }

    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("Department")]
    public string Department { get; set; }
}

[Serializable()]
[XmlRoot("EmployeesCollection")]
public class EmployeesCollection
{
    [XmlArray("Employees")]
    [XmlArrayItem("Employee", typeof(Employee))]
    public Employee[] Employee { get; set; }
}


Step 3:After adding namespace "using System.Xml.Serialization;", you can use following code to read xml data and deserialize into object for that,Create a test.aspx page with the following codes:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        EmployeesCollection students = new EmployeesCollection();
        string path = Server.MapPath("XMLFile.xml");
        XmlSerializer serializer = new XmlSerializer(typeof(EmployeesCollection));

        System.IO.StreamReader reader = new System.IO.StreamReader(path);
        students = (EmployeesCollection)serializer.Deserialize(reader);

    }
}


so , In this tutorial we have learned to Deserialize XML Document Data and Convert into .Net Array List. hope you have enjoyed this tutorial.
Happy Coding!!!!