I have the following java class
@XmlRootElement
@XmlSeeAlso(DataClass.class)
public static class EnvelopeClass {
@XmlElement
public String vers
To get the desired behaviour, you can use @XmlAnyElement on the data property instead of @XmlElement. For the @XmlAnyElement property the value will correspond to a class with the matching @XmlRootElement annotation.
EnvelopeClass
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlRootElement
@XmlSeeAlso(DataClass.class)
public class EnvelopeClass<T> {
@XmlElement
public String version;
@XmlAnyElement
public T data;
EnvelopeClass() {
}
EnvelopeClass(String version, T data) {
this.version = version;
this.data = data;
}
}
DataClass
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="data")
public class DataClass {
@XmlElement
public String name;
DataClass() {
}
DataClass(String name) {
this.name = name;
}
}
Demo
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(EnvelopeClass.class);
DataClass data = new DataClass("myName");
EnvelopeClass envelope = new EnvelopeClass<DataClass>("1.0", data);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(envelope, System.out);
}
}