Serialization/De-serialization is an essential aspect of any application, especially when it needs to communicate with another application by sending and receiving data. Generally, two different applications(also may be of different platforms) can’t understand one another’s internal data structure. In this case, XML data (Extensible Markup Language) can be a good bearer in making communication between them easier. So, now comes the requirement for the creation of XML data and constructing/retrieving data to/from XML. Although it’s possible to create the XML file manually with its own defined tag and manipulate them with LINQ to XML or so, there is a great and more efficient/quick solution from .NET for this purpose, where we can serialize/serialize a .NET class(here c# class) very easily without worrying that much.
In this tutorial, I am going to show you how to do XML serialization with c# code examples. Here I will be reading and writing a settings class. If you need a similar settings class and read/write that from your application, then you can re-use the complete class that I am going to put at the end of the post.
Serialize A C# Class To XML File:
To perform a complete XML serialization of the C# class and save it to a physical XML file, we will need the help of 2 different types of .NET classes. One is System.Xml.Serialization.XmlSerializer class(same class will be needed in De-serialization, so better importing the System.Xml.Serialization namespace at the top of the class page.), another is System.IO.StreamWriter(corresponding reader class will be used on De-serialization; both are under common namespace System.IO). The ‘XmlSerializer’ instance will do the main task of serialization, and the ‘StreamWriter’object will write the resultant serialized XML to a given file. Following are the code snippets to accomplish this:
string path = "MySettings.xml";
XmlSerializer x = new XmlSerializer(settings.GetType());
StreamWriter writer = new StreamWriter(path);
x.Serialize(writer, settings);
Code language: JavaScript (javascript)
See, it’s very simple, isn’t it? We have to call the ‘Serialize’ method with the parameters of the writer and object to serialize. Just for your information, you can also use another type of write class (such as ‘TextWriter’) also instead of ‘StreamWriter’, checkout out the available overloaded methods of the ‘Serialize’ function for more details.
After the serialization completes, you will see an XML file named ‘MySettings.xml’ in the debug directory(as it’s treated as the current directory by the application). Let’s assume we are using a settings class for which we are creating an XML file. It is as like the following code sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyApplication.Config
{
public class MySettings
{
#region Properties
/// <summary>
/// get/set the property 1
/// </summary>
private string property1= "";
public string Property1
{
get
{
return property1;
}
set
{
property1= value;
}
}
/// <summary>
/// get/set property 2
/// </summary>
private string property2= "";
public string Property2
{
get
{
return property2;
}
set
{
property2= value;
}
}
#endregion
public MySettings()
{
}
}
}
Code language: HTML, XML (xml)
For the class like above, the resultant XML file should contain texts as follows:
<?xml version="1.0" encoding="utf-8"?>
<MySettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Property1>Property1 Value</Property1>
<Property2>Property2 Value</Property2>
</MySettings>
Code language: HTML, XML (xml)
De-Serialize A XML File To C# Class:
This is also almost similar to serialization. This time, we will be using two classes, XmlSerializer and StreamReader(instead of StreamWriter). Here is the sample code to accomplish this:
MySettings settings = new MySettings();
string path = "MySettings.xml";
XmlSerializer x = new XmlSerializer(typeof(MySettings));
StreamReader reader = new StreamReader(path);
settings = (TVSettings)x.Deserialize(reader);
Code language: JavaScript (javascript)
Notice that we have to pass the type of object we are trying to De-serialize(as well as serialize), so you must have to know the type of object that will be created from the XML file.
Custom XML Serialization/De-serializer Class:
Here is the code block of a complete custom class that will read/write XML files from/to c# classes:
public class SettingsManager
{
/// <summary>
/// Write Configuration To XML File
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
public static bool Write(MySettings settings,string path)
{
try
{
XmlSerializer x = new XmlSerializer(settings.GetType());
StreamWriter writer = new StreamWriter(path);
x.Serialize(writer, settings);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Read Settings
/// </summary>
/// <returns></returns>
public static MySettings Read()
{
TVSettings settings = new MySettings(string path);
try
{
XmlSerializer x = new XmlSerializer(typeof(MySettings));
StreamReader reader = new StreamReader(path);
settings = (TVSettings)x.Deserialize(reader);
return settings;
}
catch
{
return settings;
}
}
}
Code language: PHP (php)
Purpose Of ISerializable Interface In Serialization:
You will notice that we haven’t implemented any ISerializable interface or used any ‘Serializable’/’NonSerializable’ attribute. If we can do without them, why do they exist in .NET? Ans is, Of course, it has quite a significance. There are several points to consider regarding this matter:
- Extending the ISerializable interface is required in the cases where .NET objects need to control their own serialization and De-serialization. Also, it’s used to provide custom binary serialization, usually for ‘BinaryFormatter.’
- What we just practiced is that XmlSerialization only uses properties for the process; ISerializable isn’t required here as XMLSerializer can take care of it very well.
But still, it’s always best to extend the classes from this and mark ‘NonSerialized’ for which serialization won’t use for.
XML Serialization With IXMLSerializable:
If you are writing a class that will need majorly for XML serialization, you can also follow another simple procedure than described above. Simply, just implement the IXMLSerializable interface. Then you will need to implement three methods, which will be as the following code example:
public System.Xml.Schema.XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(System.Xml.XmlReader reader)
{
throw new NotImplementedException();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
throw new NotImplementedException();
}
Code language: PHP (php)
You need to pass the write/reader (XMLReader/XMLWrite) as a parameter to do the read/write operation. There is a complete class example on IXMLSerializable MSDN documentation. You can refer to it to know more in-depth.
References:
To know more about. For NET’s serialization techniques, please refer to the MSDN doc for serialization in C# and VB. Let me know if you have any questions by commenting here. Happy coding 🙂
John Rob says
Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about reading and writing XML in C#.Net, Well done job!. As well as this post I have found an another post too which also explained very well about Reading and Writing XML file in C#.Net, you can also visit this post….
http://mindstick.com/Articles/d10f55c9-539d-4f63-bc80-0314f4ca029f/?How%20to%20read%20and%20write%20XML%20in%20C#
Thanks Everyone for your precious post!!
matbaa says
allowed us to develop application in big thank you
Mart says
Advisable is using the “using” phrase to neatly clean up writer or reader:
using (StreamReader reader = new StreamReader(path)) {
conf = (ConfigurationModes)x.Deserialize(reader);
}
Ashish says
Nice article. Short and brief but effective. There is one more article i appreciate for the beginners on XML serialization –
a1ashiish-csharp.blogspot.com/2013/05/c.net-xml-serialization-in-c-sharp-vs-2010.html
Moumni mohamed says
I don’t understand the type tvsystem and system ,for me iwant to serialize a path. ( c:/program/manager ) selected with a browserDialogue . But next time the application load directories from the same serialized path