.NET XML Serialization
Recently I needed to read and write objects to a stream in XML. The XML serialization built in to .NET makes this much easier than generating and parsing XML with your own code, or even with trusty expat. However, more complex hierarchies require a little more thought when using serialization.
For example, consider the following:
<Root>
<Parent>
<Name>foo</Name>
<Child>
<Element1>1</Element1>
</Child>
</Parent>
<Parent>
<Name>bar</Name>
<Child>
<Element2>2</Element2>
</Child>
</Parent>
</Root>
Note the different Child elements. How can we serialize/deserialize this kind of data?
public class Child1
{
public Element1 element;
}
public class Child2
{
public Element2 element;
}
public class Parent
{
[XmlAnyElement("Child")]
public object child;
private object out;
public T Deserialize<T>()
{
T inst;
if (child != null)
{
// Deserialize the node we can't predict.
XmlNodeReader r = new XmlNodeReader((XmlNode) child);
XmlSerializer s = new XmlSerializer(typeof(T));
out = inst = (T)s.Deserialize(r);
}
return inst;
}
}
public class Root
{
[XmlElement("Parent")]
public Parent parent;
}
And how do we serialize the modified child elements? We'll use a very simple subclass of XmlElement that can write itself out to a XmlWriter (I got the idea from Daniel Cazzulino's blog).
public class StubNode : XmlElement
{
private object o;
public StubNode(object o)
: base(String.empty, o.GetType().Name,
String.empty, new XmlDocument())
{
this.o = o;
}
public override void WriteTo(XmlWriter w)
{
XmlSerializer s = new XmlSerializer(o.GetType());
s.Serialize(w, o);
}
}
public partial class Parent
{
public void Preserialize()
{
if (out != null)
{
child = new ObjectNode(out);
}
}
}