Java – JAXB and inheritance in Collections
How do I map (through JAXB in Java 1.6) collections to XML and XML, and where
class mapping{ @XmlElementWrapper(name="list") @XmlElement(name="item") Collection<A> list; } abstract class A{ } class B extends A{ public String onlyB; } class C extends A{ public String onlyC; }
I want to see XML like this:
<something> (doesnt matter,I'm using it in another structure) <list> <item xsi:type="b"><onlyB>b</onlyB></item> <item xsi:type="c"><onlyC>c</onlyC></item> </list> </something>
It works if I have
class mapping{ @XmlElement(name="item") A item; }
I've tried xmlelementref, but it didn't work
I don't want to use @ xmlelements ({@ xmlelement...}) because other projects that are using it can add derived classes from a
Solution
Your mapping seems to be correct You need to make sure that you include the B and C classes when creating a jaxbcontext One way to do this is to use @ xmlseealso
@XmlSeeAlso(B.class,C.class) abstract class A{ }
The following is an example of using XSI: type to represent inheritance in a domain model using JAXB:
> http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html
If you want to use the XML schema concept of a substitution group to represent inheritance, use @ xmlelementref:
> http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html
Xmlelements corresponds to the selection structure in the XML Schema:
> http://blog.bdoughan.com/2010/10/jaxb-and-xsd-choice-xmlelements.html > http://blog.bdoughan.com/2011/04/xml-schema-to-java-xsd-choice.html
Complete example
The following is a complete example:
drafting
package forum7672121; import java.util.Collection; import javax.xml.bind.annotation.*; @XmlRootElement(name="something") @XmlAccessorType(XmlAccessType.FIELD) class Mapping{ @XmlElementWrapper(name="list") @XmlElement(name="item") Collection<A> list; }
One
package forum7672121; import javax.xml.bind.annotation.XmlSeeAlso; @XmlSeeAlso({B.class,C.class}) abstract class A{ }
B
package forum7672121; class B extends A{ public String onlyB; }
C
package forum7672121; class C extends A{ public String onlyC; }
demonstration
package forum7672121; import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Mapping.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum7672121/input.xml"); Mapping mapping = (Mapping) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true); marshaller.marshal(mapping,System.out); } }
input. XML / output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <something> <list> <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="b"> <onlyB>b</onlyB> </item> <item xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="c"> <onlyC>c</onlyC> </item> </list> </something>