• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Programming / Getting Started With XML Serialization In C#

Getting Started With XML Serialization In C#

February 12, 2011 by Rana Ahsan 5 Comments

C# Serialization Tutorial

Serialization/De-serialization is a very important feature of an application, especially when it needs to communicate with another application by sending and receiving data. Because, generally, two different applications(also may be of different platforms) can’t understand one another one’s internal data structure. In this case, XML data (Extensible Markup Language) can be a good bearer to make 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:

For performing a complete XML serialization of the C# class and saving 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 snippet 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 that we are creating an XML file of. 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. And also, it’s used to provide custom binary serialization, usually for ‘BinaryFormatter’.
  • What we just practiced, 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:

Implement ixmlserializable interface
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 like 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. NET’s serialization techniques, please refer to MSDN doc for serialization in C# and VB. Let me know if you have any questions by commenting here. Happy coding 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Programming Tagged With: .net, c#

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. John Rob says

    February 29, 2012 at 3:06 am

    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!!

    Reply
  2. matbaa says

    October 2, 2012 at 1:06 pm

    allowed us to develop application in big thank you

    Reply
  3. Mart says

    March 27, 2013 at 8:59 am

    Advisable is using the “using” phrase to neatly clean up writer or reader:
    using (StreamReader reader = new StreamReader(path)) {
    conf = (ConfigurationModes)x.Deserialize(reader);
    }

    Reply
  4. Ashish says

    May 29, 2013 at 4:14 am

    Nice article. Short and brief but effective. There is one more article i appreciate for the beginners on XML serialization –
    http://a1ashiish-csharp.blogspot.com/2013/05/c.net-xml-serialization-in-c-sharp-vs-2010.html

    Reply
  5. Moumni mohamed says

    June 24, 2017 at 6:02 pm

    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

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Getting Started With UDP Programming in Java
    Getting Started With UDP Programming in Java
  • Utilizing Config File In C#.NET Application
    Utilizing Config File In C#.NET Application
  • Generate HTTP Requests using c#
    Generate HTTP Requests using c#

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023