Tuesday, March 24, 2009

Xml Related Extensions

Given the following extension 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;
}
}
}


You can do something like:

Person person = new Person("Jack Daniels");
string xmlData = person.ToXml();
Person backFromXml = xmlData.FromXml<Person>();



...

No comments:

Post a Comment