XmlSerializer and factory-created elements
Asked Answered
Z

1

6

I am trying to serialize/deserialize objects that have factory-created members. For example, lets say there are a member of type Foo, which is instantiated using FooFactory.CreateFoo(int bar).

My current idea is to

1.create a custom XmlReader (for example, derive from XmlTextReader), and attach the factory to it

2.implement IXmlSerializable

3.in ReadXml(), I can the grab the factory from the reader.

Not sure if this is the most elegant way to do it, has anybody made similar attempts ?

Zenobiazeolite answered 21/11, 2011 at 12:27 Comment(0)
B
6

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;
Baez answered 21/11, 2011 at 12:45 Comment(1)
Thanks, DTO seems to be the way to go here ! :)Zenobiazeolite

© 2022 - 2024 — McMap. All rights reserved.