Friday, December 30, 2005 9:35 PM
Mickey Williams
FAQ: How do I serialize an arbitrary object into an XML document
Although most of the examples that you see in MSDN and elsewhere online assume a hardcoded type for an object being serilized, it's fairly easy to use a generic method that's parameterized for the object to be serialized:
void SerializeToXml<T>(T thing, string path)
{
using (XmlWriter writer = XmlTextWriter.Create(path, null))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
serializer.Serialize(writer, thing);
}
}
The client-side usage pattern is straight-forward:
SerializeToXml(myObj, @"c:\xml\myObj.xml");
You can use similar code to deserialize:
T DeserializeFromXml<T>(string path)
{
using (XmlReader reader = XmlTextReader.Create(path, null))
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(reader);
}
}
As the type of T is not discoverable in the actual parameter list, the consumer of this method must explicitly parameterize the call (note that a cast is not required):
MyObj theObj = DeserializeFromXml<MyObj>(@"c:\xml\myObj.xml");