+92 332 4229 857 99ProjectIdeas@Gmail.com

How to read object from file (XmlSerialization) (C#.net)


How to read object from file (XmlSerialization):
Serialization, as implemented in the System.Xml.Serialization namespace is the process of serializing and de-serializing objects so that they can be stored or transferred and then later re-created.  
Deserializing is the process of converting a previously serialized sequence of bytes into an object.
 
Code
 
using System.Xml.Serialization;

In this particular example we have created Employee class as Serialized. Class contains properties id and name, their getters/setters, default and parametrized constructor and one print() function. 

In XmlSerializer, we have to define the type of our object that is to be deserialized, so below in typeof() we defining the objects to of Employee type.
   
     XmlSerializer xml = new XmlSerializer(typeof(Employee));

Or,
     Employee emp = new Employee();
     XmlSerializer xml = new XmlSerializer(emp.GetType());


DESERIALIZING A SINGLE OBJECT:

public static void Main(string[] args)
{
 
Opening a file rec.xml from where to read the already written objects:
     FileStream fs = new FileStream("rec.xml", FileMode.Open, FileAccess.Read);

Creating XmlSerializer xml object of Employee type:
     XmlSerializer xml = new XmlSerializer(typeof(Employee));

.Deserialize() method takes FileStream object where to read the object, Creating an Employee  object and casting the read object from .Deserialize() to Employee:
     Employee emp = (Employee)xml.Deserialize(fs);

.print() is the class method: call it to display Employee id and name on Console.
     emp.print();

READING ALL OBJECTS FROM FILE:
 
Reading whole file and load all objects of Employee class from file, and add that objects to  List of Employee objects:
 
List<Employee> listEmployees = new List<Employee>();
FileStream fs = new FileStream("rec.xml", FileMode.Open, FileAccess.Read);
XmlSerializer xml = new XmlSerializer(typeof(Employee));
try
    {
         while (fs.CanRead)
          {
               Employee emp = (Employee)xml.Deserialize(fs);
               listEmployees.Add(emp);
          }
    }
     catch (Exception e) {}

Now, whole objects loaded in listEmployees. You can do whatever with the objects and can write those objects back also.
 
DISPLAYING ALL LOADED OBJECTS FROM LIST:
 
foreach (Employee emp in listEmployees)
          emp.print();

 
 

0 comments: