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
}
/* After Unmarshalling */
Home home ;
for(Object obj : home .getAny()){
if(obj instanceof Person ){
Person person = (Person )obj;
// .........
}else if(obj instanceof Animal ){
Animal animal = (Animal )obj;
// .........
}
}
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
.
So is there a way to achieve Animal or Person
instance that is saved in xml in "Home.any" List
.
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)
.Java Model
Home
Person
}
Animal
Demo Code
input.xml
Demo
Output
For More Information