I want to marshall a XMLAttribute in derived class, but I have some problem.
I have 2 derived class and 1 super class, as following:
public class Dog extends Animal {
@XmlAttribute(name = "type")
private String type;
@XmlElement
private String name;
}
public class Cat extends Animal {
@XmlAttribute(name = "type")
private String type;
@XmlElement
private String name;
}
@XmlSeeAlso({Dog.class, Cat.class})
public class Animal {
}
@XmlRootElement(name="some_element_wrapper")
public SomeElementWrapper() {
List<Animal> listAnimal;
@XmlElement(name = "animals")
public List<Animal> getListAnimal() {}
public void setListAnimal(List<Animal> listAnimal) {}
}
Suppose I have a List populated with some data. I want to generate XML from my classes like this :
<some_element_wrapper>
<animals>
<animal type="dog">....</animal>
<animal type="cat">....</animal>
</animals>
</some_element_wrapper>
My issue is that i get what I want except the type attribute. I tried with other different solutions, moving attribute type in super class, or overriding derived type field, but with no result. Please, any suggestion ?
Make JAXBContext
Aware of Subclasses
A JAXB (JSR-222) implementation isn't automatically aware of a mapped classes subclasses. You will either need to include them in the array of classes used to bootstrap the JAXBContext
or use an @XmlSeeAlso
annotation on one of the mapped classes.
@XmlSeeAlso(Dog.class, Cat.class)
public class Animal {
}
Inheritance Indicator
If you are looking to use the type attribute to specify the subtype being used, I would recommend not doing that and using the xsi:type
attribute instead which is how inheritance is represented in an XML (with XML an XML schema) and the default representation in JAXB.
If you really don't want to use an xsi:type
attribute, you could leverage an XmlAdapter
to use a type
attribute as the inheritance indicator.
EclipseLink JAXB (MOXy) also offers an extension (@XmlDescrinatorNode
/@XmlDescrimatorValue
) that makes this use case easier (I'm the MOXy lead).