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">开发者_C百科
<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:
<Objects>
<A>
<name></name>
<color></color>
</A>
<B>
<shape></shape>
<weight></weight>
</B>
<Objects>
And then you could have the following java:
@ElementListUnion({
@ElementList(entry = "A", inline = true, type = A.class),
@ElementList(entry = "B", inline = true, type = B.class)
}
private List<BaseClass> objects;
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:
<Objects>
<Object class="ObjectA">
<name></name>
<color></color>
</Object>
<Object class="ObjectB">
<shape></shape>
<weight></weight>
</Object>
<Objects>
Why replace your type="A"
and type="B"
attributes with classes, using a regular expression, before feeding it to the Simple XML deserializer? For instance:
xml = xml.replaceAll("type=\"([A-Za-z0-9_]+)\", "class=\"$1\"");
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.
精彩评论