The title may be long, let me explain what I mean. I won’t give you the actual XML that I need to work with, but I’ll give one that demonstrates the issue I’m facing.
I have an XML that looks like this:
<root>
<creatures>
<creature type="mammal" name="lion">
<sound>roarr</sound>
</creature>
<creature type="bird" name="parrot">
<color>red</color>
</creature>
</creatures>
</root>
Imagine the following classes:
(Of course these are not my real classes either, but you get the point.)
public class Creature
{
public string Name { get; set; }
}
public class MammalCreature : Creature
{
public string Sound { get; set; }
}
public class BirdCreature : Creature
{
public string Color { get; set; }
}
I would like to use XML Serialization with attributes in a manner that I want the serializer to distinguish between the types MammalCreature and BirdCreature by the type attribute.
I’ve found solutions that can do this by setting the xsi:type attribute to the type name I want, but I’d like to know if there is an actual solution that does this for my case.
Not with just attributes, no. However, this hairy looking code can indeed read your XML properly into a
Rootclass: