Simple XML Serialization and Deserialization using generics

by Heathesh 28. October 2010 21:06

I wanted to create a standard manager class I could use to serialize and deserialize my entity classes regardless of the type of class. I wanted the manager class to be able to write the XML out to a file, or read it from a file and return the populated class object. In order to do this, I started off with the methods to Serialize a class. But first, you need to add the following usings:

using System.IO;
using System.Text;
using System.Xml.Serialization;

Next, add the methods:

        /// <summary>
        /// Serialize class into an XML string
        /// </summary>
        /// <typeparam name="T">Type of the class</typeparam>
        /// <param name="classToSerialize">Class to serialize</param>
        /// <returns>The serialised string</returns>
        public static string SerializeToXML<T>(T classToSerialize) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(classToSerialize.GetType());
            StringBuilder stringBuilder = new StringBuilder();

            using (StringWriter writer = new StringWriter(stringBuilder))
            {
                serializer.Serialize(writer, classToSerialize);
                writer.Close();
            }

            return stringBuilder.ToString();
        }

        /// <summary>
        /// Serialize class directly to file
        /// </summary>
        /// <typeparam name="T">Type of the class</typeparam>
        /// <param name="fileName">File name and path</param>
        /// <param name="classToSerialize">Class to serialize</param>
        public static void SerializeXMLToFile<T>(string fileName, T classToSerialize) where T : class
        {
            using (StreamWriter streamWriter = new StreamWriter(fileName, false, Encoding.Unicode))
            {
                streamWriter.Write(SerializeToXML<T>(classToSerialize));
                streamWriter.Flush();
                streamWriter.Close();
            }
        }


The comments should be self explanatory, take special note of the "where T : class" clause, I added that in as a safety clause so this methods could only be run on class objects and not value types. Next I added the deserialize methods:

        /// <summary>
        /// Deserialize class
        /// </summary>
        /// <typeparam name="T">Type of object to return</typeparam>
        /// <param name="serializedObject">Serialized xml string</param>
        /// <returns>Deserialized class</returns>
        public static T DeserializeXML<T>(string serializedObject) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            T result = default(T);

            using (MemoryStream input = new MemoryStream(System.Text.Encoding.Unicode.GetBytes(serializedObject)))
            {
                input.Position = 0;
                result = (T)serializer.Deserialize(input);
                input.Close();
            }

            return result;
        }
        /// <summary>
        /// Deserialize class from file
        /// </summary>
        /// <typeparam name="T">Type of object to return</typeparam>
        /// <param name="filePath">File name and path</param>
        /// <returns>Deserialized class</returns>
        public static T DeserializeXMLFile<T>(string filePath) where T : class
        {
            T result = default(T);

            if (File.Exists(filePath))
            {
                string fileContents = System.IO.File.ReadAllText(filePath);

                if (fileContents.Length > 0)
                    result = DeserializeXML<T>(fileContents);
            }

            return result;
        }


That was pretty much it. I put the methods in a static class I named XmlManager and I've been using it to serialize and deserialize my entity classes. Simple example of how to use this:

            //create a sample person object to serialize
            Person person = new Person
            {
                Id = 1,
                FirstName = "Heathesh",
                Surname = "Bhandari",
                DateOfBirth = new DateTime(1980, 1, 1)
            };
           
            //serialize the class to xml
            string serializedXml = XmlManager.SerializeToXML<Person>(person);
            Console.WriteLine(serializedXml);

            //deserialize the xml string to the class object
            Person newPerson = XmlManager.DeserializeXML<Person>(serializedXml);
            Console.WriteLine("{0} {1} {2}", person.Id, person.FirstName, person.Surname);


Happy serializing!

Tags: , , , , ,

Development | .Net | Visual Studio 2010 | VS2010



Powered by BlogEngine.NET 1.5.0.7 (with enhancements by Heathesh)
Theme by Mads Kristensen (with tweeks by Heathesh)

Certifications

Microsoft Certified Professional

Microsoft Certified Technology Specialist

Answer Questions

 

Tag cloud

Calendar

<<  June 2017  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

View posts in large calendar

http://heathesh.com