Wednesday, February 11, 2009

Helper Class For XML Seriazliation- C#

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Inputter
{
class Helber
{
///
/// To convert a Byte Array of Unicode values (UTF-8 encoded) to a complete String.
///

/// Unicode Byte Array to be converted to String
/// String converted from Unicode Byte Array
private String UTF8ByteArrayToString(Byte[] characters)
{
UTF8Encoding encoding = new UTF8Encoding();
String constructedString = encoding.GetString(characters);
return (constructedString);
}


///
/// Converts the String to UTF8 Byte array and is used in De serialization
///

///
///
private Byte[] StringToUTF8ByteArray(String pXmlString)
{
UTF8Encoding encoding = new UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(pXmlString);
return byteArray;
}
///
/// Method to convert a custom Object to XML string
///

/// Object that is to be serialized to XML
/// XML string
public String SerializeObject(Object pObject)
{
try
{
String XmlizedString = null;
MemoryStream memoryStream = new MemoryStream();
XmlSerializer xs = new XmlSerializer(typeof(Info));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);


xs.Serialize(xmlTextWriter, pObject);
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
return XmlizedString;
}
catch (Exception e)
{
System.Console.WriteLine(e);
return null;
}
}
///
/// Method to reconstruct an Object from XML string
///

///
///
public Object DeserializeObject(String pXmlizedString)
{
XmlSerializer xs = new XmlSerializer(typeof(Info));
MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);


return xs.Deserialize(memoryStream);
}
}

[Serializable]
public class Info
{
public int id;
public string name;
}

}

Note 1: This code is extracted from that link http://www.dotnetjohn.com/articles.aspx?articleid=173

No comments:

Post a Comment