Notice: This Wiki is now read only and edits are no longer possible. Please see: https://gitlab.eclipse.org/eclipsefdn/helpdesk/-/wikis/Wiki-shutdown-plan for the plan.
EclipseLink/UserGuide/MOXy/Advanced XML Schema Concepts/Handling Null Values
EclipseLink MOXy
EclipseLink | |
Website | |
Download | |
Community | |
Mailing List • Forums • IRC • mattermost | |
Issues | |
Open • Help Wanted • Bug Day | |
Contribute | |
Browse Source |
Working with Null Values
Eclipselink offers several ways to configure its handling of null values in both Java and XML. For example, your XML may use xsi:nil to represent a null value (e.g. <first-name xsi:nil="true"/>), or it might simply use an empty element (e.g. <first-name></first-name>). On the Java side, you may want to specify exactly how a null value should be written to XML (nil or empty node). You can even specify an "isSet" method, to differentiate between values that were explicitly set to null versus values which are null due to being unset.
Consider the following schema:
<?xml version="1.0" encoding="UTF-8"?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="customer" type="customer-type"/> <xsd:complexType name="customer-type"> <xsd:element name="id" type="xsd:string"/> <xsd:element name="name" type="xsd:string"/> <xsd:element name="account-number" type="xsd:string" nillable="true"/> </xsd:complexType> </xsd:schema>
An example instance document might look like:
<customer> <id/> <name>Jon Smith</name> <account-number xsi:nil="true"/> </customer>
For this example, we would like:
- Empty id tags to correspond to null in Java
- Empty name tags to correspond to "" (empty string) in Java (this is EclipseLink's default null-handling behavior)
- A nil account-number to correspond to null in Java
To achieve this behavior in EclipseLink, our mappings can be defined using annotations as follows:
package example; import javax.xml.bind.annotation.*; import org.eclipse.persistence.oxm.annotations.*; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Customer { private String id; private String name; @XmlElement(name="account-number") @XmlNullPolicy(xsiNilRepresentNull="true" nullRepresentationForXml=XmlMarshalNullRepresentation.XSI_NIL) private String accountNumber; ... }
Here, we have specified that xsi:nil in XML should represent null in Java, and conversely, that null in Java should be represented by xsi:nil in XML.