Reputation: 21
I am having issues unmarshalling XML using the jaxb2-maven-plugin(1.5). Basically I have in my XML document, an element A of type B, which is a base domain class, Class A. Type B is a domain class that extends A. Now, I can see the XML coming in with the element A with xsi:type="B". But when I unmarshall it, it still returns a Java object of type A. How can I resolve this? I need to be able to get an object of type B. As long, as the XML has the notation xsi:type, it should be able to unmarshall it, correct. Or do I still need XMLAdapters, etc?
Thanks a lot.
Upvotes: 2
Views: 306
Reputation: 149047
There are a couple things to check:
JAXBContext
aware of the B
class? You can include in the classes used to create the JAXBContext
or add @XmlSeeAlso({B.class})
on the A
class.B
class B
? By default it will be b
. You can use the @XmlType
annotation to specify a name.A
package forum13712986;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlSeeAlso({B.class})
public class A {
}
B
package forum13712986;
import javax.xml.bind.annotation.XmlType;
@XmlType(name="B") // Default name is "b"
public class B extends A {
}
Demo
package forum13712986;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
String xml = "<A xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:type='B'/>";
StreamSource source = new StreamSource(new StringReader(xml));
JAXBElement<A> jaxbElement = unmarshaller.unmarshal(source, A.class);
System.out.println(jaxbElement.getValue().getClass());
}
}
Output
class forum13712986.B
Upvotes: 2