.net deserialize xml to one of several known objects

Having tried a search with various combinations of ".net deserialize xml one multi-known object type" ... and not finding anything that makes sense, I'm here now.

I get 1 out of 5 unrelated objects (different schemes for each) that can be sent to me, and I need to deserialize this xml into the correct object. And, of course, the number / type of objects will grow ;-) Is there a way for the deserializer to match the xml content for the object, possibly reflection (just guess)? I don't get the outer xml wrapper around the serialized object telling me what it is other than the xml content itself. These are messages coming from different systems, notifying me of an event, status change, new order, ...

I'm thinking of brute force now, the xml reader is looking for an identification attribute that uniquely matches one of my known elements, and then switches from there to deserialization using the appropriate type. It is just not too elegant.

Any guidance, G

+4
source share
2 answers

Use the following:

Stream xml; // Contains the XML to deserialize XmlSerializer xmlSerializer = new XmlSerializer( typeof(MyClass1), new []{ typeof(MyClass2), typeof(MyClass3) }); // Add additional classes here object obj = xmlSerializer.Deserialize(xml); if(obj Is MyClass1) { // Do something } else if (obj is MyClass2) { // Do something } else if (obj is MyClass3) { // Do something } // And so on for other classes 
0
source

If the name of the XML root element (and / or namespace) is different for each type of object, you can use XmlSerializer.CanDeserialize to check the name of the root element for the schema.

 XmlSerializer appleSerializer = new XmlSerializer(typeof(Apple)); XmlSerializer bananaSerializer = new XmlSerializer(typeof(Banana)); XmlSerializer carrotSerializer = new XmlSerializer(typeof(Carrot)); XmlReader reader = XmlReader.Create(file); if (appleSerializer.CanDeserialize(reader)) { Apple a = (Apple)appleSerializer.Deserialize(reader); // ... } else if (bananaSerializer.CanDeserialize(reader)) { Banana b = (Banana)bananaSerializer.Deserialize(reader); // ... } else if (carrotSerializer.CanDeserialize(reader)) { Carrot c = (Carrot)carrotSerializer.Deserialize(reader); // ... } 
0
source

Source: https://habr.com/ru/post/1432611/


All Articles