Unmarshal Subtypes / Inheritance

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Unmarshal Subtypes / Inheritance

Stephan Arlt
Hi,

I got the following three Java classes:

(1) class A {}
(2) class B extends A {}
(3) class C extends A {}

Furthermore, I got the following XML content:

<A type="B"></A>
<A type="C"></A>

Can you provide a quick note on how to unmarshal the XML content into the Java classes B and C?

BTW: I guess it would perfectly suit XStream's tutorial page, since it is a common scenario.

Thanks,
Stephan
---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


Reply | Threaded
Open this post in threaded view
|

Re: Unmarshal Subtypes / Inheritance

Jörg Schaible-2
Hi Stephan,

Stephan Arlt wrote:

> Hi,
>
> I got the following three Java classes:
>
> (1) class A {}
> (2) class B extends A {}
> (3) class C extends A {}
>
> Furthermore, I got the following XML content:
>
> <A type="B"></A>
> <A type="C"></A>
>
> Can you provide a quick note on how to unmarshal the XML content into the
> Java classes B and C?
>
> BTW: I guess it would perfectly suit XStream's tutorial page, since it is
> a common scenario.

Well, not necessarily for XStream, because XStream is "from Java to XML and
back", i.e. XStream defines the XML structure and ensures that the same
object graph can be created later again.

You can tweak the XML to some extend, but in any case you should always
start to write your objects to XML first, only then you can understand what
kind of XML XStream does read - or why yours is not read as you thought ;-)

Since a converter in XStream is always responsible for the content of a tag,
but never for the tag itself, it is difficult to say something really useful
for your XML snippet.

Some examples:

================ %< ==================
class X {
 A anA;
 X(A a) { anA = a; }
}

new A() ==> "<A/>"
new B() ==> "<B/>"
new A[]{ new A(), new B()} ==> "<A-array><A/><A class="B"/></A-array>"
new X(new A()) ==> "<X><anA/></X>"
new X(new B()) ==> "<X><anA class="B"/></X>"
================ %< ==================

As you can see, the tag name depends on the location of the A/B instance in
the object graph as well as the "class" attribute, that is written if a
declared type does not match the type of the instance exactly.

You can define a system alias for the "class" attribute to "type", but I
cannot say, if this es enough to match your requirement. Otherwise you will
need a custom converter that can handle any kind of A instance and declare a
type alias.

- Jörg


---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email