I frequently need to store and retrieve object state. I’ve found the .NET Framework’s XmlSerializer invaluable in this capacity. To make my life even easier, I’ve come up with a pair of functions that serialize and deserialize an arbitrary object to an XML file.
I’ve stripped out comments, exception handling, etc. for brevity’s sake.
public void Serialize(object obj, string path)
{
XmlSerializer ser = new XmlSerializer(obj.GetType());
XmlTextWriter writer = new XmlTextWriter(path, System.Text.Encoding.UTF8);
writer.Formatting = Formatting.Indented;
ser.Serialize(writer, obj);
writer.Close();
}
public object Deserialize(Type type, string path)
{
object obj = null;
XmlSerializer ser = new XmlSerializer(type);
XmlTextReader reader = new XmlTextReader(path);
obj = ser.Deserialize(reader);
reader.Close();
return obj;
}
One noteworthy caveat to this technique is that XmlSerializer will only serialize public instance fields and public properties with both get and set defined.
Example C# usage:
public class Address
{
public string Name;
public string Line1;
public string City;
public string State;
public string Zip;
}
Address a = new Address();
a.Name = "John Doe";
a.Line1 = "123 Main St.";
a.City = "Anytown";
a.State = "NY";
a.Zip = "10900";
Serialize(a, @"c:tempaddress.xml");
Address a = Deserialize(typeof(Address), @"c:tempaddress.xml") as Address;
Notice I use the “as” keyword instead of casting. I prefer to use this form since it yields null on conversion failure instead of raising a NullReferenceException.
The resulting XML from the above example looks like:
<p>
<?xml version=”1.0″ encoding=”utf-8″?>
</p>
<p>
<Address xmlns:xsd=”http://www.w3.org/2001/XMLSchema” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”>
</p>
<p>
<Name>John Doe</Name>
</p>
<p>
<Line1>123 Main St.</Line1>
</p>
<p>
<City>Anytown</City>
</p>
<p>
<State>NY</State>
</p>
<p>
<Zip>10900</Zip>
</p>
<p>
</Address>
</p>
<p>
</span>
</p>
<p>
This stuff gets pretty interesting when dealing with complex object graphs.
</p>