Inheritance with Simple XML Framework

那年仲夏 提交于 2019-12-07 19:46:21

问题


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..


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6846904/inheritance-with-simple-xml-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!