对于此示例,您将要使用@XmlElementRef
和@XmlRootElement
注释。这对应于替代组的XML模式概念。这将允许您获得继承层次结构中由元素区分的对象列表。
动物
这将作为根对象为域模型。它有一个List
财产注释与@XmlElementRef
。这意味着它将根据其@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;
}
猫
我们将注释Cat
类的@XmlRootElement
注解。这与Animals
上的@XmlElementRef
注释串联使用。
package forum8356849;
import javax.xml.bind.annotation.*;
@XmlRootElement(name="Cat")
class Cat extends Animal
{
int numLives;
}
狗
我们也将增加一个@XmlRootElement
注释到Dog
类。
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);
}
}
对于更多Inforation
谢谢!我会给它一个! – fbl
啊,我遇到了一个小障碍......我的应用程序需要支持插件,'@XmlSeeAlso({Cat.class,Dog.class})'意味着我需要在编译时了解我的后代。有什么办法呢? – fbl
@fbl - 您不需要使用XmlSeeAlso,但JAXBContext需要知道子类。您可能会发现以下方法更适合:http://blog.bdoughan.com/2010/08/using-xmlanyelement-to-build-generic.html –