I assume you want to use the XmlSerializer. If you need "polymorphic" deserialization, you can pass a list of types that the serializer should know about (this works if they all inherit from the same base class, but not from the interface).
Example:
List<Type> extraTypes = new List<Type>(); extraTypes.Add(typeof(multiple)); extraTypes.Add(typeof(add)); extraTypes.Add(typeof(substract)); extraTypes.Add(typeof(divide)); var ser = new XmlSerializer(typeof(Foo), extraTypes.ToArray());
It explains: Serializing and restoring an unknown class
But there is another problem: in your XML, your operand can contain two different types: an operation or a parameter (a, b, c, d), and you cannot represent it in your class.
Something that I usually see is (I implemented only the add operation, and I assume that the expression is numeric):
public class Expression { public virtual int Evaluate() { } } public class Add : Expression { Expression _left; Expression _right; public Add(Expression left, Expression right) { _left = left; _right = right; } override int Evalute() { return _left.Evalute() + _right.Evalute(); } } public class Parameter : Expression { public int Value{get;set;} public Parameter(string name) {
Thus, you have only one base class, so everything is simpler. If that makes sense, I think it would be impractical to deserialize it.
EDIT: If the base class is a calculator (instead of an expression), the XML will look like this:
<Calculator xsi:type="Multiple"> <calculators> <Calculator xsi:type="Add"> <calculators> <Calculator xsi:type="Operator"> <value>12</value> </Calculator> </calculators> </Calculator> </calculators> </Calculator>
I created a simple calculator object and serialized it and what I got. If you do deserialization, you get a calculator that will return 12.
Perhaps you can use XmlAttributes to change element names in XML, or in the worst case write your own deserializer.