usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Xml;
usingSystem.IO;
usingSystem.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>
privatestaticstringUTF8ByteArrayToString(byte[] characters)
{
UTF8Encodingencoding =newUTF8Encoding();
stringconstructedString = 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>
privatestaticByte[] StringToUTF8ByteArray(stringpXmlString)
{
UTF8Encodingencoding =newUTF8Encoding();
byte[] byteArray = encoding.GetBytes(pXmlString);
returnbyteArray;
}
/// <summary>
///Serialize an object into an XML string
///</summary>
///<typeparam name="T"></typeparam>
///<param name="obj"></param>
///<returns></returns>
publicstaticstringSerializeObject<T>(T obj)
{
try
{
stringxmlString =null;
MemoryStreammemoryStream =newMemoryStream();
XmlSerializerxs =newXmlSerializer(typeof(T));
XmlTextWriterxmlTextWriter =newXmlTextWriter(memoryStream,Encoding.UTF8);
xs.Serialize(xmlTextWriter,obj);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
xmlString = UTF8ByteArrayToString(memoryStream.ToArray()); returnxmlString;
}
catch
{
returnstring.Empty;
}
}
///<summary>
///Reconstruct an object from an XML string
///</summary>
///<param name="xml"></param>
///<returns></returns>
publicstaticT DeserializeObject<T>(stringxml)
{
XmlSerializerxs =newXmlSerializer(typeof(T));
MemoryStreammemoryStream =newMemoryStream(StringToUTF8ByteArray(xml));
XmlTextWriterxmlTextWriter =newXmlTextWriter(memoryStream,Encoding.UTF8);
return(T)xs.Deserialize(memoryStream);
}