JAXB: Namespace annotation not inherited during unmarshalling - regression in JDK 1.8_102?

∥☆過路亽.° 提交于 2019-12-30 22:55:14

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/40889384/jaxb-namespace-annotation-not-inherited-during-unmarshalling-regression-in-jd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!