David
David

Reputation: 1841

Non-intrusive XML Serialization techniques?

I have long held the believe that your domain model should not be responsible for serializing itself to XML. I have used the IXmlSerializable interface in the past to control how my objects are serialized but ideally I'd prefer the nuts and bolts of the serialization to live outside the object.

However I've never been able to actually implement this in a clean manner and I was wondering if there was any patterns I was overlooking to make this happen. Basically I want my object model to do it's thing and be oblivious to XML serialization (or any other serialization for that matter) and then handed off to some service that spiders the object and serializes it.

I've tried doing this with extension methods but this falls short when you want to serialize a collection of type object. I've looked at doing it with object wrappers and DTO's that then serialize but then you've got the overhead of maintaining another set of objects and having to create these objects when you want to serialize which again can get messy when you have collections of type object.

The only other thing is using reflection but I'd worry about the processing overheads.

Is there a sane way to do what I'm asking or should I just bite the bullet and make my objects xml aware?

Upvotes: 1

Views: 165

Answers (1)

Gusdor
Gusdor

Reputation: 14334

Using the System.Xml.Serialization Attributes is putting the nuts and bolts outside of your code. You are defining metadata and with the exception of optional parameters, no extra code is required. Implementing IXmlSerializable and doing the serialization by hand is error prone and should be avoided. Why? You are defining your data 3 times.

  1. XML Schema
  2. Class
  3. Serialization code

Using attributes, you can scrub step 3.

XML and C# has an impedance mismatch. Like it or not, at some point, you will need to define the serialization to create the right document model.

Arguably, the classes you are serializing should not be performing any work. They are just a data store. Try abstracting your logic away from serialized objects - it may give you a warmer feeling.

Update

If you really, really hate attributes, try using the adapter pattern to serialize your model. The XML code will be in a separate class or assembly and you can work with your model across storage mediums. You will suffer the consequence of having to update the serialization separately when you update your model.

Upvotes: 1

Related Questions