Tuesday, May 15, 2012

XML serialization and deserialization in C#.net



Here my idea to avoid the serialization for the basic types. So the  demo purpose I am skipping serialization for the strings.

private string SerializeAnObject(object obj)
        {
            if (obj.GetType() == string.Empty.GetType())
            {
                return (string)obj;
            }
            System.Xml.XmlDocument doc = new XmlDocument();
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType());
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            try
            {
                serializer.Serialize(stream, obj);
                stream.Position = 0;
                doc.Load(stream);
                return doc.InnerXml;
            }
            catch
            {
                throw;
            }
            finally
            {
                stream.Close();
                stream.Dispose();
            }

        }

In the below code I am explicitly passing the xRoot object i.e. root object of your xml data which is serialized previously. Here xRoot is mandatory otherwise the decryption is not possible.

This method Internally calls deserialize method to deserilaize the data

public UsersInfo FillProdcutsOrderSessionData(string xmlData)
        {
            ProductOrderModel productsOrderModel = new ProductOrderModel();
            XmlRootAttribute xRoot = new XmlRootAttribute();
            xRoot.ElementName = "UserInforModel";
            xRoot.IsNullable = true;
            object deserializedData = DeSerializeAnObject(xmlData, xRoot, productsOrderModel.GetType());
            UsersInfo usersInfo = (UsersInfo)deserializedData;
return usersInfo;

        }




/// <summary>
        /// Deserialze the data
        /// </summary>
        /// <param name="xmlOfAnObject">Xml data which is got stored when serialization happens</param>
        /// <param name="xRoot">xRppt Object</param>
        /// <returns></returns>
        private object DeSerializeAnObject(string xmlOfAnObject, XmlRootAttribute xRoot)
        {

            UsersInfo myObject = new UsersInfo ();
            System.IO.StringReader read = new StringReader(xmlOfAnObject);
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(myObject.GetType(), xRoot);
            System.Xml.XmlReader reader = new XmlTextReader(read);
            try
            {
                myObject = (UsersInfo)serializer.Deserialize(reader);
                return myObject;
            }
            catch (Exception ex)
            {
                throw;
            }

            finally
            {
                reader.Close();
                read.Close();
                read.Dispose();
            }

        }






No comments:

Post a Comment