I ran into a situation where JAXB refuses to unmarshal an XML element unless the corresponding Java field has a namespace annotation. This behavior only started in JDK 1.8.0_111 (or possibly in 102). Earlier versions of JDK 1.8 work.
Test case:
Java class (shortened):
package my.package;
@XmlRootElement(name = "MyElement", namespace="myns")
public class MyElement {
@XmlElement(name = "subEl")
private String subEl;
}
XML:
<MyElement xmlns="myns">
<subEl>text1</subEl>
</MyElement>
package-info.java:
@XmlSchema(elementFormDefault = XmlNsForm.QUALIFIED)
package my.package;
Unmarshalling code:
JAXBContext jc = JAXBContext.newInstance(MyElement.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
MyElement myel = (MyElement) unmarshaller.unmarshal(xmlStream);
System.out.println("Parse result: "+ myel);
With JDK 1.8.0_101 (and earlier) this prints:
Parse result: MyElement [subEl=subEl]
With JDK 1.8.0_111 I get:
Parse result: MyElement [subEl=null]
So JDK 1.8.0_111 refuses to unmarshal the element "MyElement".
If I specify the namespace on the field annotation:
@XmlElement(name = "subEl", namespace="myns")
private String subEl;
it works as expected in all JDK versions.
What is going on here?
As far as I understand, the setting elementFormDefault = XmlNsForm.QUALIFIED
should cause all fields of class MyElement to "inherit" the namespace of the class. The Javadocs for @XmlElement
say:
If the value is "##default", then the namespace is determined as follows:
If the enclosing package has XmlSchema annotation, and its elementFormDefault is QUALIFIED, then the namespace of the enclosing class. Otherwise '' (which produces unqualified element in the default namespace.
Default: "##default"
So why does JDK 1.8.0_111 not unmarshal the element?
Note: JAXB bug report #1087 - Unmarshalling Wrapped elements with elementForName=qualified fails (formerly at JAXB-1087- Unmarshalling Wrapped elements with elementForName=qualified fails) seems to report the same problem - no response so far.
I think this is the relevant bug - https://bugs.openjdk.java.net/browse/JDK-8165299
From which I can say that there was indeed a fix for JAXB. So this strange behavior which ends up in null values is a wrong JAXB mapping and not a regression in Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With