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 = new memorystream ();
Xmlserializer xs = new xmlserializer (typeof (t ));
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> (string XML)
{
Xmlserializer xs = new xmlserializer (typeof (t ));
Memorystream = new memorystream (stringtoutf8bytearray (XML ));
Xmltextwriter = new xmltextwriter (memorystream, encoding. utf8 );
Return (t) XS. deserialize (memorystream );
}
Posted
On Friday, July 20,200 am | Back to Top