+92 332 4229 857 99ProjectIdeas@Gmail.com

How to write a object in file (XmlSerialization) (C#.net)



How to write a object in file (XmlSerialization):
XmlSerialization, as implemented in the System.Xml.Serialization namespace is the process of serializing and deserializing objects so that they can be stored or transferred and then later re-created.
Serializing is the process of converting an object into a linear sequence of bytes that can be stored or transferred.


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 serialized, 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());


SERIALIZING A SINGLE OBJECT:

public static void Main(string[] args)
{ 
 
Create, Employee class object:
  Employee employee = new Employee(12, "osama");


Now, we have to save these objects in file, so open a file:
  FileStream fs = new FileStream("emp.xml", FileMode.Create, FileAccess.Write);
 
Now, write or serialize the whole object to that open file, so create XmlSerializer class object first, and use its .Serialize() method which takes two arguments first the FileStream class object and the second is that object (here that object is of Employee class) which is to be written or serialized:
   XmlSerializer xml = new XmlSerializer(typeof(Employee));
   xml.Serialize(fs, employee);
}

Now, if you open "emp.xml" file, you would see an object is stored in the following format: 

<Employee>
  <id> 12 </id>
  <name> osama </name>
</Employee>

SERIALIZING A LIST OF OBJECTS:

FileStream fs = new FileStream("employee.xml", FileMode.Create, FileAccess.Write);
XmlSerializer xml = new XmlSerializer(typeof(Employee));
ArrayList recordList = new ArrayList();

   recordList.Add(new Employee(12, "osama"));  
   recordList.Add(new Employee(13, "saad"));  
   recordList.Add(new Employee(14, "amal"));
   recordList.Add(new Employee(15, "maryam"));
   recordList.Add(new Employee(16, "bilal"));  
 
   for (int i = 0; i < recordList.Count; i++)

    {
    
     Employee emp = (Employee)recordList[i];
     xml.Serialize(fs, record);
     fs.Flush();

   }

0 comments: