我创建了三个JAXB类:Home , Person , Animal
。 Java类
Home有变量List<Object> any
,可能包含Person和/或Animal实例。
public class Home {
@XmlAnyElement(lax = true)
protected List<Object> any;
//setter getter also implemented
}
@XmlRootElement(name = "Person") // Edited
public class Person {
protected String name; //setter getter also implemented
}
@XmlRootElement(name = "Animal") // Edited
public class Animal {
protected String name; //setter getter also implemented
}
/ * 解组后 * /
Home home ;
for(Object obj : home .getAny()){
if(obj instanceof Person ){
Person person = (Person )obj;
// .........
}else if(obj instanceof Animal ){
Animal animal = (Animal )obj;
// .........
}
}
我需要在Person or Animal
变量中保存"Home.any" List
个对象,但"Home.any" List
的内容是com.sun.org.apache.xerces.internal.dom.ElementNSImpl
的实例,而不是Animal or Person
。
那么有没有办法实现Animal or Person
中保存在xml中的"Home.any" List
实例。
答案 0 :(得分:5)
您需要在要使用@XmlRootElement
注释的字段/属性中将要显示为实例的类添加@XmlAnyElement(lax=true)
。
主强>
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlAccessorType(XmlAccessType.FIELD)
public class Home {
@XmlAnyElement(lax = true)
protected List<Object> any;
//setter getter also implemented
}
人
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Person")
public class Person {
}
<强>动物强>
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Animal")
public class Animal {
}
<强> input.xml中强>
<?xml version="1.0" encoding="UTF-8"?>
<root>
<Person/>
<Animal/>
<Person/>
</root>
<强>演示强>
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance(Home.class, Person.class, Animal.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource xml = new StreamSource("src/forum20329510/input.xml");
Home home = unmarshaller.unmarshal(xml, Home.class).getValue();
for(Object object : home.any) {
System.out.println(object.getClass());
}
}
}
<强>输出强>
class forum20329510.Person
class forum20329510.Animal
class forum20329510.Person