Thursday, August 13, 2009

Object to XML and XML to Object

I always need this code... so now its on my page!


internal static class XmlSerializerHelper
{
public static object GetObjectFromXml(string xml, Type type)
{
XmlSerializer ser = new XmlSerializer(type);
object value = ser.Deserialize(new StringReader(xml));
return value;
}

public static string GetXmlFromObj(object obj, Type type)
{
string xml;
XmlSerializer ser = new XmlSerializer(type);
using (StringWriter writer = new StringWriter())
{
ser.Serialize(writer, obj);
writer.Flush();
xml = writer.ToString();
}

return xml;
}

public static string ToXml(this object obj)
{
Type type = obj.GetType();
string xml = GetXmlFromObj(obj, type);
return xml;
}

}

No comments: