JAXB / XJC generates a JAXBElement <String>, not just a String (to handle the null case)

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

My XSD is disabled here:

<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 created class 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 that JAXB uses JAXBElement to resolve null, but that doesn't make sense, since anything declared as String can be null.

And I have no way to change the XSD, because my client would prefer to 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

+7
java xml xsd jaxb
source share
2 answers

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

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

This will allow you to build the following XML scripts:

  • The element must not be present in the XML document when the property is null.
  • An element must be present in XML with xsi:nil="true" when the property is JAXBElement when the nil flag is set.

To get rid of JAXBElement , you can use the generateElementProperty option as f1sh answers , but then you will not be able to process both scripts.

Additional Information

See my answer to the relevant question:

  • Convert nil = "true" to zero during non-marshal operation
+8
source share

Check if you can pass arguments to the code generator (xjc). I once had one problem, but I was able to solve the problem by setting generateElementProperty to false. Here is how I did it.

This is a definitely defined option for the jaxb code generator and should be able to shut down.

EDIT: According to xjc.exe /? you can use the binding file with the -b option.

+3
source share

All Articles