Let’s have an XML list of people:
and an object model of list items:
What we can see here is the mismatch between two domains – a strongly typed OO domain and loosely typed text domain. The mismatch can be resolved using different approaches, for example we could build a set of tags over class members to help the XmlSerializer to deal with plain text data. But trying to be as naive as possible we could provide a helper method which, for given XmlNode, would return a typed value of an attribute.
The conversion of untyped text data to typed class instances require the knowledge of member signatures:
Although such naive approach is common, it has obvious disadvantages. Basically we duplicate the model metadata description on both sides of assignments. The mismatch is still there waiting to bite when models change – if names/types change, we’d have to apply manual changes on one/both sides of above assignments. In particular, refering to members using literal names could possibly bite badly as there’s no chance to catch possible mismatch during the compilation.
The intention of this entry is to document another common approach, a one step further than what is presented above. Note once again that each assignment of a form:
contains the same information twice – the name and type of of a class member matches the name of XML attribute, however we have to repeat this information on the right side of the assignment.
Let’s then provide a new extension:
This time we require an expression denoting model member, rather than a separate information of its name and type. This allows us to rewrite the client code to:
The possibilities of further enhancements are endless and even such simple one is a significant one as possible mismatch between models can now be caught by the compiler.