Tuesday, October 21, 2008

Another peace of code that I don't want to rewrite it again (and again)
using System;
using System.Collections.Generic;

/// <summary>
/// This class uses XmlSerializer to do both sides of conversion to xml string
/// </summary>
/// <typeparam name="T">any Serializable class</typeparam>
public class Serializer<T>
{
/// <summary>
/// Convert an instance to XML string
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public string Serialize(T item)
{

MemoryStream ms
= new MemoryStream();
XmlTextWriter writer
= new XmlTextWriter(ms, Encoding.Unicode);

XmlSerializer serializer
= new XmlSerializer(typeof(T));
serializer.Serialize(writer, item);

writer.Flush();
ms.Position
= 0;

StreamReader reader
= new StreamReader(ms);
return reader.ReadToEnd();

}
/// <summary>
/// another version, could be better
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private string GetSerialize2(T item)
{
StringWriter wr
= new StringWriter(new StringBuilder());

XmlSerializer serializer
= new XmlSerializer(typeof(T));
serializer.Serialize(wr, item);

wr.Close();
return wr.GetStringBuilder().ToString();
}

/// <summary>
/// Convert the XML string to an instance of an object
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public T Deserialize(string xml)
{
XmlTextReader stream
= new XmlTextReader(new StringReader(xml));
XmlSerializer serializer
= new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stream);
}
}

No comments: