Code Snippets

Serialize Object to XML in C# | Write Object Data to XML File in C#

This article guides you to serialize object to XML in C#. Below is a complete example to show writing the data stored in a class object to an XML file.

C# object to XML

How to Write Object Data to an XML File in C# ( Serialize C# Object to XML File)?

Serialization is the process of converting an object into XML or binary format.

XML  serialization converts all the public fields and properties of an object into an XML file/string.This is Serialization of the class object.

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

Code Sample – Serialize Object to XML in C# ( Write Class to an XML File)

This code example XmlSerializer class for writing the C# object from a class to an XML file.

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

/// 
/// Method to serialize the Employee Object.Method which creates an object of the Data object. 
///
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); 
   } 
}
///
/// The Employee class whose object will be serialized 
/// 
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();
}

The result of Serialize Class Object 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> 
    <Name>Mohan</Name> 
    <Location>India</Location> 
    <Designation >Software Developer</Designation > 
</Department>

Convert Object To XML – Sample 2

private string ConvertObjectToXml(object objectToConvert)
{
   XmlDocument xmlDocument = new XmlDocument(); //Represents an XML document,
   //Create a new instance of the XmlDocument class.
   XmlSerializer xmlSerializer = new XmlSerializer(objectToConvert.GetType());
   // Creates a stream whose back store is memory.
   using (MemoryStream xmlStream = new MemoryStream())
   {
       xmlSerializer.Serialize(xmlStream, objectToConvert);
       xmlStream.Position = 0;
       //Loads XML document from the string specified.
       xmlDocument.Load(xmlStream);
      //return the inner xml from the xml document;
   }
   return xmlDocument.InnerXml;
}

Summary

This post covered how to serialize object data to XML in C# with sample code. Hope you got a clear understanding of how to write Object Data to an XML file in C#. Please leave your queries and feedback in the comments section below.

Rajeev

Recent Posts

OWIN Authentication in .NET Core

OWIN (Open Web Interface for .NET) is an interface between web servers and web applications…

2 years ago

Serializing and Deserializing JSON using Jsonconvertor in C#

JSON (JavaScript Object Notation) is a commonly used data exchange format that facilitates data exchange…

2 years ago

What is CAP Theorem? | What is Brewer’s Theorem?

The CAP theorem is also known as Brewer's theorem. What is CAP Theorem? CAP theorem…

2 years ago

SOLID -Basic Software Design Principles

Some of the Key factors that need to consider while architecting or designing a software…

2 years ago

What is Interface Segregation Principle (ISP) in SOLID Design Principles?

The Interface Segregation Principle (ISP) is one of the SOLID principles of object-oriented design. The…

2 years ago

What is Single Responsibility Principle (SRP) in SOLID Design Priciples?

The Single Responsibility Principle (SRP), also known as the Singularity Principle, is a software design…

2 years ago