Is there a native way to map the following xml…
<Tag type="1" />
<Tag type="2" />
… to the concrete classes “Type1Tag” and “Type2Tag” (both deriving from abstract class Tag), based on the value of the “type” attribute?
(something similar to NHibernate’s discriminator: DiscriminateSubClassesOnColumn(…)/DiscriminatorValue(…) )
I’m not looking for something like the mapping reported in XmlSerializer + Polymorphism , which discriminates types by the tag name, instead of by an attribute value (I can’t change the xml structure) 🙂
I’m probably too late in your implementation to be of any help, but this is something I figured out this weekend and thought I’d share for other people to find as it seems to meet my needs.
Please note that there is no error handling here, and you can create your own child object type initialization depending on your needs.
I have a number of different classes that are all of the same type of element, but could hold different content based on the value of an attribute.
I used the
IXmlSerializable-interface and implemented the method to read each type tag…Xml Input:
The parent class is what implements
IXmlSerializable:I created an abstract
TagBase-class that each tag type would inherit:Then, each other class can be implemented normally with your custom properties, etc…
Note, that I used
XmlRootAttributehere and included them, as I had a bunch of namespaces that caused exceptions when trying to deserialize the child tags, but YMMV. I also haven’t gotten to the point of adding theWriteXml-method, but should be pretty straight forward here…