Вы хотите использовать @XmlElementRef, это соответствует концепции схемы XML групп замещения, соответствующей вашему вопросу.
Шаг 1 - Использование @ XmlElementRef
Свойство fruitList аннотировано @XmlElementRef:
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Project {
@XmlAttribute
private String name;
@XmlElementRef
private List<Fruit> fruitList = new ArrayList<Fruit>();
}
Шаг 2 - аннотируйте Apple и Orange с помощью @ XmlRootElement
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Apple extends Fruit {
@XmlAttribute
private String appleKey;
}
и
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Orange extends Fruit {
@XmlAttribute
private String orangeKey;
}
Демонстрационный код
Следующий код может быть использован для демонстрации решения:
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Project.class, Apple.class, Orange.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Project project = (Project) unmarshaller.unmarshal(new File("input.xml"));
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(project, System.out);
}
}
Для получения дополнительной информации: