Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB/XJC generates JAXBElement<String> rather than just String (to handle null case)

Tags:

java

xml

jaxb

xsd

Using JAXB/xjc shipped with JDK 1.7 (bin\xjc.exe)

Here's a snipped of my XSD:

<xs:complexType name="NameType">
    <xs:sequence>
      <xs:element name="Surname" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>
      <xs:element name="Firstname" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>
      <xs:element name="Middlename" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>
    </xs:sequence>
</xs:complexType>

The class generated shows:

@XmlElementRef(name = "Surname", type = JAXBElement.class, required = false)
protected JAXBElement<String> surname;

public JAXBElement<String> getSurname() {
    return surname;
}
public void setSurname(JAXBElement<String> value) {
    this.surname = value;
}

I understand JAXB is using JAXBElement to allow for null,but this makes no sense since anything declared as a String can be set to null.

And I don't have the option of changing the XSD, because my client would rather leave the existing XSD in production.

Question: Can I change the code generator to generate:

@XmlElementRef(name = "Surname", type = String.class, required = false)
protected String surname;

public String getSurname() {
    return surname;
}
public void setSurname(String value) {
    this.surname = value;
}

Thanks Joel

like image 431
joellucuik Avatar asked Oct 24 '14 13:10

joellucuik


2 Answers

By default a JAXBElement is generated when an XML element is both nillable and optional.

<xs:element name="Surname" type="xs:string" nillable="true" minOccurs="0" maxOccurs="1"/>

This is to allow you to construct XML the following scenarios:

  1. The element should be absent from the XML document when the property is null.
  2. The element should be present in the XML with a value of xsi:nil="true"when the property is a JAXBElement when the nil flag set.

To get rid of the JAXBElement you can use the generateElementProperty option as answered by f1sh, but then you won't be able to handle both scenarios.

For More Information

See my answer to a related question:

  • Convert nil="true" to null during unmarshal operation
like image 152
bdoughan Avatar answered Nov 10 '22 20:11

bdoughan


Check if you can pass arguments to your code generator (xjc). I had the same problem once but was able to solve the problem by setting generateElementProperty to false. Here's how i did it.

This is definitely some option on the jaxb code generator and should be able to switch off.

EDIT: According to xjc.exe /? you can spedify the bindings file with the -b parameter.

like image 5
f1sh Avatar answered Nov 10 '22 19:11

f1sh