hid*_*ser 6 java jaxb eclipselink jaxb2 xml-parsing
我创建了三个JAXB类:Home , Person , Animal
。Java Class 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
}
Run Code Online (Sandbox Code Playgroud)
/ * 解组后 * /
Home home ;
for(Object obj : home .getAny()){
if(obj instanceof Person ){
Person person = (Person )obj;
// .........
}else if(obj instanceof Animal ){
Animal animal = (Animal )obj;
// .........
}
}
Run Code Online (Sandbox Code Playgroud)
我需要实现将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
。
您需要@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
}
Run Code Online (Sandbox Code Playgroud)
人
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Person")
public class Person {
Run Code Online (Sandbox Code Playgroud)
}
动物
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="Animal")
public class Animal {
}
Run Code Online (Sandbox Code Playgroud)
input.xml
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
}
Run Code Online (Sandbox Code Playgroud)
演示版
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出量
class forum20329510.Person
class forum20329510.Animal
class forum20329510.Person
Run Code Online (Sandbox Code Playgroud)