JAXB avoid JAXBElement<?>

六眼飞鱼酱① 提交于 2019-11-29 03:48:04

The Problem

The problem is that your xs:choice element has maxOccurs="unbounded".

<xs:choice minOccurs="0" maxOccurs="unbounded">

JAXB Spec Reference

Because of this JAXB can't generate individual properties for each option in the choice structure. See "6.12.6 Bind a repeating occurrence model group" of the JAXB 2.2 (JSR-222) specification for more details:

Why it's a Problem

The following XML fragment is valid according to your XML schema and needs to be able to be represented in the generated object model.

<Action>
    <DocumentID/>
    <PatientID/>
    <PatientID/>
    <DocumentID/>
</Action>

Work Around

If you ever really don't like a class that JAXB generates you can create your own and specify via a bindings file that JAXB should use it instead of creating a new one.

<jxb:bindings schemaLocation="yourSchema.xsd">
    <jxb:bindings node="//xs:element[@name='Action']">
        <jxb:class ref="com.example.Action"/>
    </jxb:bindings>
</jxb:bindings>

I wrote the Simpify plugin exactly for this problem.

<xs:schema ...
    xmlns:simplify="http://jaxb2-commons.dev.java.net/basic/simplify"
    jaxb:extensionBindingPrefixes="... simplify">

<xs:complexType name="typeWithReferencesProperty">
    <xs:choice maxOccurs="unbounded">
        <xs:element name="a" type="someType">
            <xs:annotation>
                <xs:appinfo>
                    <simplify:as-element-property/>
                </xs:appinfo>
            </xs:annotation>
        </xs:element>
        <xs:element name="b" type="someType"/>
    </xs:choice> 
</xs:complexType>

will give you

@XmlElement(name = "a")
protected List<SomeType> a;
@XmlElement(name = "b")
protected List<SomeType> b;

instead of

@XmlElementRefs({
    @XmlElementRef(name = "a", type = JAXBElement.class),
    @XmlElementRef(name = "b", type = JAXBElement.class)
})
protected List<JAXBElement<SomeType>> aOrB;

Disclaimer: I'm the author.

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