Serialize objects in Custom XML Format Using XML Serialization Attributes

Introduction

The code shows how to apply XML serialization attributes and their functionality. The code shows how these attributes format the XML generated by serialization.

This code contains a class named Institute, which stores institute information and has some public fields and an array field, which contains objects of another class called Employee. In the Main method, you create and initialize an object of Institute and then serialize it to an XML file and Institute.xml Finally, you deserialize it into another object of Institute.

Code

public class Institute
{
   
//XML Attribute Declaration
   [XmlAttribute]
   
public string Name;
   [
XmlAnyAttribute]
   
public XmlAttribute[] xAttributes;
   [
XmlAnyElement]
   
public XmlElement[] XElement;
   [
XmlElement(ElementName = "Students")]
   
public Student[] Students;
   
static void Main(string[] args)
   {
      
//Specify xml file path
      string file = "Institute.xml";
      
//XML Serializer Class Declaration for serializing class institute
      XmlSerializer XS = new XmlSerializer(typeof(Institute));
      
//Declarating of text writer
      TextWriter TW = new StreamWriter(file); 
      
Institute IS = new Institute();
      IS.Name = 
"NIIT"
      
Student ST = new Student();
      ST.Name = 
"Kailash";
      ST.ID = 
"S32";
      ST.RegisterNo = 
"R31"
      
Student ST1 = new Student();
      ST1.Name = 
"Ramsharan";
      ST1.ID = 
"S33";
      ST1.RegisterNo = 
"R32"
      IS.Students = 
new Student[2] { ST, ST1 };
      
//Serialize to institute
      XS.Serialize(TW, IS); 
      TW.Flush();
      TW.Dispose();
      TW.Close(); 
      
FileStream FS = new FileStream(fileFileMode.Open);
      
Institute IS1 = (Institute)XS.Deserialize(FS);
      
Console.WriteLine(IS1.Name);
      
Console.WriteLine("--------------------------------------");
      
Console.WriteLine("Student List");
      
Console.WriteLine("------------");
      
foreach (Student st in IS1.Students)
      {
          
Console.WriteLine(" ");
          
Console.WriteLine(st.Name);               
          
Console.WriteLine(st.ID);
          
Console.WriteLine(st.RegisterNo);               
      }
      
Console.ReadLine();
   }
}