I'm using the Simple XML Framework for parsing XML files.
From a server i receive a XML-File what looks like this:
<Objects>
<Object type="A">
<name></name>
<color></color>
</Object>
<Object type="B">
<shape></shape>
<weight></weight>
</Object>
<Objects>
I have an interface (or superclass) Object and two subclasses A and B
Is it possible to de-serialize this XML-Document?
I saw in the Tutorial that there is a possibility to differentiate between subclasses with an class-attribute, but unfortunately this is not possible for me. Is there a way to chose that the framework chooses the right sub-class on the base of the type attribute?
I can't use another Framework (like JAXB) because i use Android..
Simple XML can do that too if you are willing to make one minor change to your XML. So in your example, you could change that xml to look like this:
And then you could have the following java:
And that is all that there really is to it. Though I do not think that it can be done based on an Attribute. I could be wrong though, you might want to read the docs for that one.
This'll be tricky to do if you can't use the class attribute, like so:
Why replace your
type="A"
andtype="B"
attributes with classes, using a regular expression, before feeding it to the Simple XML deserializer? For instance:I was able to use this trick parsing XML generated by .NET's XML serializer, which uses the attribute
xsi:type
to indicate the specific class type in polymorphic lists such as this one.