Marshal XMLAttribute in a derived class

I want marshall XMLAttribute in a derived class, but I have some problems.

I have 2 derived classes and 1 superclass as shown below:

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 filled with some data. I want to generate XML from my classes as follows:

 <some_element_wrapper> <animals> <animal type="dog">....</animal> <animal type="cat">....</animal> </animals> </some_element_wrapper> 

My problem is that I get what I want, except for the type attribute. I tried using other solutions, moving the attribute type to the superclass or overriding the derived field, but with no result. Please any suggestion?

+4
source share
1 answer

Make JAXBContext Maintenance

A JAXB implementation (JSR-222) does not automatically know about subclasses of associated classes. You will need to include them in an array of classes used to bootstrap JAXBContext , or use the @XmlSeeAlso annotation for one of the associated classes.

 @XmlSeeAlso(Dog.class, Cat.class) public class Animal { } 

Inheritance indicator

If you want to use the type attribute to indicate the subtype to be used, I would recommend not to do this and use the xsi:type attribute instead, namely, how inheritance is represented in XML (with XML XML Schema) and the default representation in JAXB.

If you really don't want to use the xsi:type attribute, you can use the XmlAdapter to use the type attribute as an indicator of inheritance.

EclipseLink JAXB (MOXy) also offers an extension ( @XmlDescrinatorNode / @XmlDescrimatorValue ) that does this (I am the leader of MOXy).

+1
source

Source: https://habr.com/ru/post/1441246/


All Articles