Click here to Skip to main content
Licence 
First Posted 19 Sep 2006
Views 55,371
Downloads 559
Bookmarked 33 times

XMLFormatter provider for serialization

By Patrick Boom | 25 Sep 2006
Creating a custom XMLFormatter for serialization of objects.

1

2
1 vote, 11.1%
3
3 votes, 33.3%
4
5 votes, 55.6%
5
4.56/5 - 9 votes
μ 4.56, σa 1.27 [?]

Introduction

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.

Alternatives

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.

XmlFormatter

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
{
    [Serializable]
    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 = " + 
                           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);
        }
#endregion
    }
}

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:");
            Console.WriteLine(object1.GetProperties());
            Console.WriteLine();
            // 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:");
            Console.WriteLine(xml.Value);
            Console.WriteLine();
            
            // 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(object2.GetProperties());
            Console.WriteLine();
            Console.WriteLine("Press any key to continue");
            Console.ReadKey();
        }
    }
}

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!

License

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

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionchanged or missing member results in exception Pinmemberapoplex20087:52 14 Dec '11  
GeneralQuestion regarding Attributes Pinmemberlhayes006:12 27 Jan '09  
Questionserialization of arrays Pinmembersqueelydan2:26 22 Aug '07  
Generalplz help me PinmemberaliCarryme1:56 22 Aug '07  
GeneralProblems with a non ISerializable implementing class PinmemberChris Richner14:30 13 Aug '07  
GeneralGood idea! Pinmemberppschmitz3:36 14 Feb '07  
GeneralIList handling Pinmemberlmarrou22:23 27 Jan '07  
GeneralGenerics PinmemberCommonGenius7:33 26 Nov '06  
GeneralXMLFormatter vs. Generics PinmemberKeith Vinson7:54 3 Oct '06  
GeneralRe: XMLFormatter vs. Generics PinmemberPatrick Boom22:02 3 Oct '06  
GeneralRe: XMLFormatter vs. Generics PinmemberKeith Vinson5:39 4 Oct '06  
Yes, the XMLSerializer will still be there. The XMLFormnatter is much like the binary formatter in its functionality. But I have not studied its details. And yes, the whole 2.0 vs 3.0 is a tad confusing. The new XMLFormatter came from the Indigo, aka WCF extensions...
 
Keith
GeneralRe: XMLFormatter vs. Generics PinmemberPatrick Boom23:30 4 Oct '06  
QuestionDiscussion about the XmlFormatter class? PinmemberM.Lansdaal10:54 28 Sep '06  
AnswerRe: Discussion about the XmlFormatter class? PinmemberPatrick Boom0:03 2 Oct '06  
GeneralRe: Discussion about the XmlFormatter class? PinmemberM.Lansdaal6:37 2 Oct '06  
GeneralNice idea Pinmemberdchrno9:22 20 Sep '06  
GeneralRe: Nice idea PinmemberPatrick Boom22:15 20 Sep '06  
GeneralShame Pinmembernorm .net22:43 19 Sep '06  
GeneralRe: Shame PinmemberNinjaCross0:04 21 Sep '06  
GeneralRe: Shame PinmemberPatrick Boom22:04 3 Oct '06  

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

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

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