Click here to Skip to main content
11,930,449 members (55,783 online)
Click here to Skip to main content
Add your own
alternative version


35 bookmarked

XMLFormatter provider for serialization

, 25 Sep 2006
Rate this:
Please Sign up or sign in to vote.
Creating a custom XMLFormatter for serialization of objects.


During the development process of our project, the need arose to serialize objects to XML. For this purpose, the .NET provides the XmlSerializer class to serialize objects. This class has some disadvantages, however.

First, the creation of the class is expensive in performance. This is caused by the fact the class creates an in-memory assembly to quickly read and write from the objects to serialize. It does this by using reflection to inspect the object. This leads to the second disadvantage; only public properties and fields are serialized. These properties also have to be writable so that the XmlSerializer can set the properties during deserialization. This leads to problems encapsulating your code. Finally, but not less important, it does not support the ISerializable interface.


To get around these problems, you can use the SoapFormatter class to serialize the object to SOAP. This class does support the ISerializable interface, and does not use reflection. The resulting XML, however, is less accessible than the plain XML the XmlSerializer produces, and has a lot of overhead. The only thing left is to create your own formatter by implementing the IFormatter interface.


The code accompanied by this article contains our XmlFormatter class that has the following features:

  • Produces more clean XML than the SOAP structure of the SoapFormatter
  • Supports the ISerializable interface
  • Does not impact performance by creating in-memory assemblies

The following example shows the use of the formatter, by serializing a class called MyObject:

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
namespace XmlFormatterSample
    public class MyObject : ISerializable
        public string MyPublicProperty
            get { return _myPublicProperty; }
            set { _myPublicProperty = value; }
        private string _myPublicProperty;
        private string MyPrivateProperty
            get { return _myPrivateProperty; }
            set { _myPrivateProperty = value; }
        private string _myPrivateProperty;
        public MyObject()
            this._myPublicProperty = "This is my public property";
            this._myPrivateProperty = "This is my private property";
        public string GetProperties()
            string properties = "MyPublicProperty = " + 
                                 MyPublicProperty + "\r\n";
            properties += "MyPrivateProperty = " + 
        return properties;
#region ISerializable Members
        /// <summary>
        /// Special serialization constructor.
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public MyObject(SerializationInfo info, 
                        StreamingContext context)
            _myPublicProperty = info.GetString("MyPublicProperty");
            _myPrivateProperty = info.GetString("MyPrivateProperty");
        /// <summary>
        /// Interface method to place the properties
        /// in the serialization queue
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public void GetObjectData(SerializationInfo info, 
                                  StreamingContext context)
            info.AddValue("MyPublicProperty", MyPublicProperty);
            info.AddValue("MyPrivateProperty", MyPrivateProperty);

The following code serializes and deserializes the object from and to a MemoryStream using our XmlFormatter. Please note that both the public and the private properties are being serialized.

using DotNetMagazine.September.Examples;
using System.IO;
using System.Xml;
using System.Data.SqlTypes;
namespace XmlFormatterSample
    class Program
        static void Main(string[] args)
            MyObject object1 = new MyObject();
            MyObject object2;
            // write the properties to the console
            Console.WriteLine("The properties of object1 are:");
            // serialize the object 
            // ***************************************
            MemoryStream stream = new MemoryStream();
            XmlFormatter serializer = 
               new XmlFormatter(typeof(MyObject));
            serializer.Serialize(stream, object1);
            // reset the stream to the beginning
            stream.Position = 0;
            SqlXml xml = new SqlXml(stream);
            // ***************************************
            // write the XML value to the console
            Console.WriteLine("Xml value of object 1:");
            // recreate the object in object 2
            using (MemoryStream stream2 = 
                   new MemoryStream(Encoding.UTF8.GetBytes(xml.Value)))
                object2 = (MyObject)serializer.Deserialize(stream2);
            // write the properties to the console
            Console.WriteLine("The properties of object2 are:");
            Console.WriteLine("Press any key to continue");

The code is free to use in your projects. This code is also part of an article published in the Dutch version of the .NET magazine, September issue 2006: "Objecten en Sql Server 2005, XML als intermediair". We hope this formatter will be of use to you!


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Patrick Boom
Web Developer
Netherlands Netherlands
Patrick Boom works as a Software Engineer at Capgemini Netherlands for the last 6 years.

You may also be interested in...

Comments and Discussions

QuestionWhat is the license governing the source code Pin
SGUS18-Nov-14 0:23
memberSGUS18-Nov-14 0:23 
Questionchanged or missing member results in exception Pin
apoplex200814-Dec-11 7:52
memberapoplex200814-Dec-11 7:52 
GeneralQuestion regarding Attributes Pin
lhayes0027-Jan-09 6:12
memberlhayes0027-Jan-09 6:12 
Questionserialization of arrays Pin
squeelydan22-Aug-07 2:26
membersqueelydan22-Aug-07 2:26 
Generalplz help me Pin
aliCarryme22-Aug-07 1:56
memberaliCarryme22-Aug-07 1:56 
GeneralProblems with a non ISerializable implementing class Pin
Chris Richner13-Aug-07 14:30
memberChris Richner13-Aug-07 14:30 
GeneralGood idea! Pin
ppschmitz14-Feb-07 3:36
memberppschmitz14-Feb-07 3:36 
GeneralIList handling Pin
lmarrou27-Jan-07 22:23
memberlmarrou27-Jan-07 22:23 
GeneralGenerics Pin
CommonGenius26-Nov-06 7:33
memberCommonGenius26-Nov-06 7:33 
GeneralXMLFormatter vs. Generics Pin
Keith Vinson3-Oct-06 7:54
memberKeith Vinson3-Oct-06 7:54 
GeneralRe: XMLFormatter vs. Generics Pin
Patrick Boom3-Oct-06 22:02
memberPatrick Boom3-Oct-06 22:02 
GeneralRe: XMLFormatter vs. Generics Pin
Keith Vinson4-Oct-06 5:39
memberKeith Vinson4-Oct-06 5:39 
GeneralRe: XMLFormatter vs. Generics Pin
Patrick Boom4-Oct-06 23:30
memberPatrick Boom4-Oct-06 23:30 
QuestionDiscussion about the XmlFormatter class? Pin
M.Lansdaal28-Sep-06 10:54
memberM.Lansdaal28-Sep-06 10:54 
AnswerRe: Discussion about the XmlFormatter class? Pin
Patrick Boom2-Oct-06 0:03
memberPatrick Boom2-Oct-06 0:03 
GeneralRe: Discussion about the XmlFormatter class? Pin
M.Lansdaal2-Oct-06 6:37
memberM.Lansdaal2-Oct-06 6:37 
GeneralNice idea Pin
dchrno20-Sep-06 9:22
memberdchrno20-Sep-06 9:22 
GeneralRe: Nice idea Pin
Patrick Boom20-Sep-06 22:15
memberPatrick Boom20-Sep-06 22:15 
GeneralShame Pin
norm .net19-Sep-06 22:43
membernorm .net19-Sep-06 22:43 
GeneralRe: Shame Pin
NinjaCross21-Sep-06 0:04
memberNinjaCross21-Sep-06 0:04 
GeneralRe: Shame Pin
Patrick Boom3-Oct-06 22:04
memberPatrick Boom3-Oct-06 22:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.151126.1 | Last Updated 25 Sep 2006
Article Copyright 2006 by Patrick Boom
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid