JAXB解组@XmlAnyElement [英] JAXB Unmarshalling @XmlAnyElement
问题描述
我创建了三个JAXB类: Home,Person,Animal
。 Java类
主页具有变量 List< Object>任何可能包含Person和/或Animal实例的
。
I have created three JAXB class : Home , Person , Animal
. Java Class
Home have variable List<Object> any
that may contain Person and/or Animal instance .
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;
// .........
}
}
我需要实现保存在 Home.any List
变量中的 Person或Animal
对象,但内容 Home.any列表
是 com.sun.org.apache.xerces.internal.dom.ElementNSImpl
的实例而不是动物或人
。
I need to achieve Person or Animal
object saved in "Home.any" List
variable but content of "Home.any" List
is instance of com.sun.org.apache.xerces.internal.dom.ElementNSImpl
instead of Animal or Person
.
那么有没有办法实现动物或人
实例,该实例保存在 Home.any列表中。
So is there a way to achieve Animal or Person
instance that is saved in xml in "Home.any" List
.
推荐答案
您需要在要显示为用<$ c $注释的字段/属性中作为实例的类上添加 @XmlRootElement
c> @XmlAnyElement(lax = true)。
You need to add @XmlRootElement
on the classes you want to appear as instances in the field/property you have annotated with @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
更多信息
- http://blog.bdoughan.com/2012/12 /jaxbs-xmlanyelementlaxtrue-explained.html
- http://blog.bdoughan.com/2012/12/jaxbs-xmlanyelementlaxtrue-explained.html
For More Information
这篇关于JAXB解组@XmlAnyElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!