TechyMedia

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

NAVIGATION - SEARCH

Write Class Data to an XML File in C# | serialize c# xml

XmlSerializer class is used for writing/storing the class object data to an XML file. This is Serialization of class object. C# - Write Class Data to an XML File code sample. XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());

Below example shows writing the data stored in a class object to an XML file. 

Here Serialize method from the XmlSerializer class is used for writing/storing the class object data to an XML file.

This is Serialization of class object.

 

Code: C# - Write Class Data to an XML File 

Include using System.Xml.Serialization namespace and using System.IO to the top of the class.     

     /// <summary>
    /// Method to serialize the Employee Object.Method which creates an object of the Data object.
    /// </summary>
    public void SerializeTheObject()
    {
        Employee objectToSerialize = new Employee();
        objectToSerialize.Name = "Rajeev";
                    objectToSerialize.Location = "India";
                    objectToSerialize.Designation = "Software Developer";
 
        XmlSerializer xmlSerializer =
            new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType());
                                //use using so that streamWriter object will be disposed after use.
                    using(StreamWriter streamWriter = new StreamWriter("D:\\TestXml.xml"))
        {
                                    xmlSerializer.Serialize(streamWriter, objectToSerialize);
        }
         
    }
 
   /// <summary>
   /// The Employee class whose object will be serialized
/// </summary>     class Employee
    {         public string Name { get; set; }         public string Location { get; set; }         public string Designation { get; set; }     }

    Usage : 

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

    private void button1_Click(object sender, EventArgs e)
    {
        SerializeTheObject();
    }

   Result of Serialize Class To XML: 

   After executing the code go and check your D drive (since D:\TestXML.xml in this example).You will see your TestXML.xml file.

   XML file will look as below.             

<?xml version="1.0" encoding="UTF-8"?>
 -<Employee xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Name>Rajeev</Name>
      <Location>India</Location>
      <Designation>Software Developer</Designation>
  </Employee>

 

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading