Serialize and Deserialize object as XML

If you ever wanted to store an in memory obejct, i think serialization is the best possible method to do so, so is when you want to transport an object, i was using this for a long time now, now i have modified it a bit with generics

using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.Serialization;
 
/// <summary>
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
/// </summary>
/// <param name="characters">Unicode Byte Array to be converted to String</param>
/// <returns>String converted from Unicode Byte Array</returns>
private static string UTF8ByteArrayToString(byte[] characters)
{
   UTF8Encoding encoding = new UTF8Encoding();
   string constructedString = encoding.GetString(characters);
   return (constructedString);
}
 
/// <summary>
/// Converts the String to UTF8 Byte array and is used in De serialization
/// </summary>
/// <param name="pXmlString"></param>
/// <returns></returns>
private static Byte[] StringToUTF8ByteArray(string pXmlString)
{
   UTF8Encoding encoding = new UTF8Encoding();
   byte[] byteArray = encoding.GetBytes(pXmlString);
   return byteArray;
}
 
/// <summary>
/// Serialize an object into an XML string
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeObject<t>(T obj)
{
   try
   {
      string xmlString = null;
      MemoryStream memoryStream = new MemoryStream();
      XmlSerializer xs = new XmlSerializer(typeof(T));
      XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
      xs.Serialize(xmlTextWriter, obj);
      memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
      xmlString = UTF8ByteArrayToString(memoryStream.ToArray());      return xmlString;
   }
   catch
   {
      return string.Empty;
   }
}
 
/// <summary>
/// Reconstruct an object from an XML string
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static T DeserializeObject</t><t>(string xml)
{
   XmlSerializer xs = new XmlSerializer(typeof(T));
   MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(xml));
   XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
   return (T)xs.Deserialize(memoryStream);
}
</t>

2 Responses to “Serialize and Deserialize object as XML”

  1. vinay says:

    It is not working for GridView
    Please help me, how we serialize and deserialize GirdView

  2. naresh says:

    Hello Vinay ,

    Try and serialize and deserialize the data source of a grid view rather than grid view itself
    For me to help you more please send a code snippet of what you are trying to achive.

Leave a Reply