Monday, September 14, 2009

Xml Serialization Helper Class


public static class XmlHelper
{
public static string ToXml(this object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj);
return sw.ToString();
}
}

public static T FromXml<T>(this string data)
{
XmlSerializer s = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(data))
{
object obj = s.Deserialize(reader);
return (T)obj;
}
}
}



So we can do this:


string personString = person.ToXml();
Person newPerson = personString.FromXml<Person>();

No comments:

Post a Comment