Generic XML Serialization Class

We had to add XML Serialization functionality to a bunch of different classes. Here is a nice generic class for adding static methods for Serialization and Deserialization to any of your classes...

Well any class that doesn't inherit from another class. In that case, I guess you can use it as a standalone class. Regardless, it's good enough for me at 6:15PM on a Friday evening in the office when I'm trying to get out of here.

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

namespace HRXml
{
    public class GenericXmlSerialization<T>
        where T : class
    {
        public static T Deserialize(string input)
        {
            XmlSerializer serialization = new XmlSerializer(typeof(T));
            StringReader reader = new StringReader(input);
            object result = serialization.Deserialize(reader);
            return result as T;
        }
        public static Stream Serialize(T input)
        {
            XmlSerializer serialization = new XmlSerializer(typeof(T));
            MemoryStream results = new MemoryStream(4096);
            serialization.Serialize(results, input);
            results.Position = 0;
            return results;
        }

        public static string SerializeToString(T input)
        {
            Stream stream = Serialize(input);
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }
    }
}

This can be added to different classes by inheriting from the GenericXmlSerialization class with the current type as the Generic type.

public partial class AssessmentOrderRequestType : GenericXmlSerialization<AssessmentOrderRequestType>
{
   // STUFF HERE
}

public partial class AssessmentOrderAcknowledgementType : GenericXmlSerialization<AssessmentOrderAcknowledgementType>
{                
   // STUFF HERE
}

Or you can use it standalone.

var stream = GenericXmlSerialization<AssessmentOrderAcknowledgementType>.Serialize(myobject);

Time to get out of here!

Recent comments