This question already has an answer here:
- Issue with namespaces in XMLs in JAXB unmarshalling 1 answer
I have a simple xml to unmarshall. But I get only an empty list in the output. No exceptions are thrown. This is a third party generated xml and I need to make this work without any changes in the xml.
The XML:
<Animal xmlns="http://allmycats.com/serviceplatform/1.0/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Cat z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<name>kitty</name>
</Cat>
<Cat z:Id="i2" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/">
<name>kitty2</name>
</Cat>
</Animal>
The POJO bean for Animal:
@XmlRootElement(name = "Animal",namespace = "http://allmycats.com/serviceplatform/1.0/")
public class Animal{
List<Cat> cats;
@XmlElement(name = "Cat")
public List<Cat> getCats() {
return cats;
}
public void setCats(List<Cat>cats) {
this.cats= cats;
}
}
The POJO bean for Cat
@XmlRootElement(name = "Cat")
public class Cat {
private String zId;
private String name;
@XmlAttribute(name = "Id", namespace="http://schemas.microsoft.com/2003/10/Serialization/")
public String getzId() {
return zId;
}
public void setzId(String zId) {
this.zId = zId;
}
@XmlElement(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The unmarshall code is:
File file = new File(filepath);
System.out.println("file exists? : "+ file.exists()); // prints true
JAXBContext jaxbContext = JAXBContext.newInstance(Animal2.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Animal2 animals = (Animal2)jaxbUnmarshaller.unmarshal( file );
System.out.println("--file size: "+animals.getCats().size());
The last line gives a null pointer exception.
Am I doing something wrong with the namespaces in the BEAN classes? I am new to Jaxb and this issue is bugging me for 3 days now ! I asked this question earlier but couldn't get proper answer and this is a more precise question.