对于本示例,您将需要使用 @XmlElementRef 和 @XmlRootElement 注释。这对应于替换组的 XML 模式概念。这将允许您拥有一个按元素区分的继承层次结构中的对象列表。
动物
这将作为域模型的根对象。它有一个带有@XmlElementRef 注释的List 属性。这意味着它将根据 @XmlRootElement 注释的值匹配值。
package forum8356849;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="Animals")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({Cat.class, Dog.class})
public class Animals {
@XmlElementRef
private List<Animal> animals;
}
动物
package forum8356849;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
class Animal
{
String name;
}
猫
我们将使用@XmlRootElement 注释来注释Cat 类。这与Animals 上的@XmlElementRef 注释一起使用。
package forum8356849;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="Cat")
class Cat extends Animal
{
int numLives;
}
狗
我们还将在Dog 类中添加一个@XmlRootElement 注释。
package forum8356849;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="Dog")
class Dog extends Animal
{
boolean hasSpots;
}
演示
您可以使用以下类来查看一切是否按预期工作。 input.xml 对应于您问题中提供的 XML。
package forum8356849;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Animals.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum8356849/input.xml");
Animals animals = (Animals) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(animals, System.out);
}
}
更多信息