To XML and back
I’ve had cause recently to think about how to get from objects to XML and vice versa. The default way in .NET is to use XML Serialization. And with WCF, there’s the DataContractSerializer and NetDataContractSerializer. Add a few attributes to your class and voilà.
But there seems to be a catch. What happens when the XML changes – maybe as a result of an updated schema? You modify all of your attributes and recompile. Maybe. Depends on the object model you picked. Using the attributes encourages you to pick an object model that closely resembles the XML – there are even tools that’ll generate the code from the XML and vice versa. So you end up with code that’s tightly coupled to the format of the XML. And if your object model is tightly coupled to the XML, there’s a chance your data model will be, too. If that’s the case, you’re not going to like the impact of changes to the XML. If we’ve learned one thing by now, it’s that things change. The problem here is that each class in the object model has more than one responsibility – one of those being transforming to and from a representation in XML.
What’s the alternative? XPath for going from XML to object. As an aside, nspectre can read XML configuration files. There’s no deserialisation. There’s a bunch of XPath statements in a reader class. When I added a schema to nspectre, all I had to do was update the XPath. With this technique you could even externalise the XPath statements or have multiple readers that can read from different representations without having to modify the main body of code. This technique is being referred to as XML data duck typing. Read some more about it here and here. And when it comes to transforming from objects to XML, I’m thinking templates.
If you follow this approach you do have to write a little more code. But you gain an enormous amount of flexibility and freedom.