tags:

views:

702

answers:

2

I have a java application that i want to save the data in xml instead of a database. We decided to go with jaxb and instead of generating files based on the schema, we just added annotations to our java files. The issue we are running into is that we have an arraylist of an abstract class called Node. A Node has subclasses of either Module or ScreenImage. When we marshall the arraylist, it doesn't save the type. Such as " xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="Module". Does jaxb support elements that are abstract? How do i get jaxb to save the type, so that i'm able to unmarshall it?

+2  A: 

It should work fine. Note that if your Module and ScreenImage are not statically accessible from the bound classes (i.e. the classes specified in JAXBContext.newInstance(...)), they should be bound explicitly (add them to the JAXBContext.newInstance(...) parameters).

axtavt
That was it. I thought newInstance was only for the root elements. Thanks!
mdamman
+2  A: 

axtavt's suggestion is fine. I just want to add another approach. You could make use of @XmlSeeAlso, where you can declare other classes that should defined and visible to JAXBContext. You only have to make sure to declare the annotation within a class that is already visible to JAXBContext.

e.g.:

@XmlRootElement
@XmlSeeAlso({Node.class, Module.class, ScreenImage.class})
class SomeContent {
  private List<Node> nodes;
  ///... accessors
}
Grzegorz Oledzki