|
using System;
using System.IO ;
using System.Xml;
using System.Xml.Serialization ;
using System.Text ;
namespace SampleConsole
{
/// <summary>
/// Summary description for XmlSerializerClass.
/// </summary>
public class XmlSerializerClass
{
public XmlSerializerClass()
{
//
// TODO: Add constructor logic here
//
}
public static void TestObjactToXML()
{
Employee objEmp=new Employee();
objEmp.EmpNumber=1001;
objEmp.EmpName="Arindam Chakraborty";
string _str =GetXml(objEmp);
Employee emp =GetObject(_str);
Console.WriteLine("Example of Object to XML");
Console.WriteLine("========================");
Console.WriteLine(_str);
Console.Read();
}
public static string GetXml(Employee emp)
{
MemoryStream stream = null;
TextWriter writer = null;
try
{
stream = new MemoryStream(); // read xml in memory
writer = new StreamWriter(stream, Encoding.Unicode) ;
// get serialise object
XmlSerializer serializer = new
XmlSerializer(typeof(Employee));
serializer.Serialize(writer, emp); // read object
int count = (int) stream.Length; // saves object in
memory stream
byte[] arr = new byte[count];
stream.Seek(0, SeekOrigin.Begin);
// copy stream contents in byte array
stream.Read(arr, 0, count);
UnicodeEncoding utf = new UnicodeEncoding(); // convert
byte array to string
return utf.GetString(arr).Trim();
}
catch (Exception ex)
{
return ex.ToString();
}
finally
{
if(stream != null) stream.Close();
if(writer != null) writer.Close();
}
}
/// <summary>
/// Get a populated object from xml string
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public static Employee GetObject(string xml)
{
StringReader stream = null;
XmlTextReader reader = null;
try
{
// serialise to object
XmlSerializer serializer = new
XmlSerializer(typeof(Employee));
stream = new StringReader(xml); // read xml data
reader = new XmlTextReader(stream); // create
reader
// covert reader to object
return (Employee)serializer.Deserialize(reader);
}
catch
{
return null;
}
finally
{
if(stream != null) stream.Close();
if(reader != null) reader.Close();
}
}
}
}
|