TechyMedia

A .NET Technology blog | .NET,C# Progamming,C# tutorials,WPF WCF|Software Engineer

NAVIGATION - SEARCH

Deserialize XML to object c#

Deserialize XML to object c# -Reading the data stored in a XML file to a class object.Deserialize method from the XmlSerializer class is used for reading/deserializing the XML file data to the class object.Sample Method to Deserialize the xml file.Method which creates an object and deserialize the xml data to the object .

Below example shows Reading the data stored in a XML file to a class object.Here Deserialize method from the XmlSerializer class is used for reading/deserializing the XML file data to the class object.

 

This is Deserialization of XML to class object.

 

In this example  we will Deserialize the xml file Department.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<Department>
  <Name>Engineering</Name>
  <Location>Bangalore,India</Location>
  <Phone>080-85006600</Phone>
</Department> 

Code: Read Data from an XML File to a Class in C# - Deserialize xml to object c#

     /// <summary>

    /// Method to Deserialize the xml file.Method which creates an object and deserialize the xml data to the object .

    /// </summary>   

 internal Department DeserializeTheObject()
{         Department objectToDeserialize = new Department();         XmlSerializer xmlserializer =             new System.Xml.Serialization.XmlSerializer(objectToDeserialize.GetType());           //use using so that streamReader object will be cleaned up properly after use.         using (StreamReader streamReader = new StreamReader("D:\\Department.xml"))         {             return (Department)xmlserializer.Deserialize(streamReader);         }            } 

 

   /// <summary>

    /// The Employee class whose object will be serialized

    /// </summary>

internal class Department
{       public string Name { get; set; }       public string Location { get; set; }       public string Phone { get; set; } }

   Usage : 

 

   Call the Deserialize Object method from desired code location.I called it from a button click event in my form as below.

    Deserialized data displayed using messagebox.

private void button1_Click(object sender, EventArgs e)
 {
       Deaprtment dept = DeserializeTheObject();
                                MessageBox.show (", Department Name: "+ dept.Name + ", Location :"+ dept.Location + ", Phone : "+dept.Phone)
 }

 

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading