12 October 2014

XML Serialization and Deserialization using generics

I love generics, and I when I come across a requirement where I had  to serialize a variety of objects to xml and deserialize back to the object, generics was the way to go, and resulted in following methods.

        // De-Serializes the request into type object
        public static XmlDocument SerializeToXml(T objectToSerialize)
            XmlDocument serializedXml = new XmlDocument();
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (MemoryStream momoryStream = new MemoryStream())
                XmlTextWriter xmlTextWriter = new XmlTextWriter(momoryStream, null);

                xmlSerializer.Serialize(xmlTextWriter, objectToSerialize);
                // Rewind the Stream.
                momoryStream.Seek(0, SeekOrigin.Begin);
                // load from stream;

            return serializedXml;

        // De-Serializes the request into class object
        public static T DeserializeXml(XmlNode xmlToDesearialized)
            if (xmlToDesearialized == null) throw new ArgumentNullException("xmlToDesearialized");
            T deserializedObject = default(T);
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

            using (StringReader stringReader = new StringReader(xmlToDesearialized.OuterXml))
                XmlTextReader xmlTextReader = new XmlTextReader(stringReader);
                deserializedObject = (T)xmlSerializer.Deserialize(xmlTextReader);
            return deserializedObject;

No comments:

Post a Comment