XmlSerializer
simply isn't set up for that. I would strongly suggest that if you want to use XmlSerializer
, your best bet would be to map your data to a simpler DTO model first, and serialize that. When writing code back from the DTO to your model, add the factory creation there, in regular code. The DTO model should be simple; simple enough for XmlSerializer
to be happy with it.
Yes, implementing IXmlSerializable
is an option, however: that API is very hard to get 100% right (to handle all the various ways xml can appear to it). I find that API very hard, and I do a lot of serialization. I humbly submit that writing a few lines of code to map from your main model to a DTO model is a lot more robust (and a lot quicker) than trying to implement IXmlSerializable
.
For example, you could have:
[XmlRoot("foo")]
public class FooDTO {
[XmlAttribute("bar")]
public int Bar {get;set;}
public static implicit operator Foo(FooDTO value)
{
return value == null ? null : FooFactory.Create(value.Bar);
}
public static implicit operator FooDTO(Foo value)
{
return value == null ? null : new FooDTO { Bar = value.Bar; }
}
}
then you can convert from Foo
to FooDTO
simply by:
Foo foo = ...
FooDTO dto = foo;