You can specify this behaviour using MOXy's NullPolicy. You will need to create a DescriptorCustomizer to modify the underlying mappings. Don't worry it's easier than it sounds, I'll demonstrate below:
import org.eclipse.persistence.config.DescriptorCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.oxm.mappings.XMLCompositeObjectMapping;
import org.eclipse.persistence.oxm.mappings.nullpolicy.XMLNullRepresentationType;
public class RootEntityCustomizer implements DescriptorCustomizer {
@Override
public void customize(ClassDescriptor descriptor) throws Exception {
XMLCompositeObjectMapping entityTwoMapping = (XMLCompositeObjectMapping) descriptor.getMappingForAttributeName("entityTwo");
entityTwoMapping.getNullPolicy().setNullRepresentedByEmptyNode(true);
entityTwoMapping.getNullPolicy().setMarshalNullRepresentation(XMLNullRepresentationType.EMPTY_NODE);
}
}
Below is how you associate the customizer with your model class:
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.persistence.oxm.annotations.XmlCustomizer;
@XmlRootElement(name="RootEntity")
@XmlCustomizer(RootEntityCustomizer.class)
public class RootEntity {
private String attributeOne;
private Entity entityOne;
private Entity entityTwo;
@XmlElement(name="AttributeOne")
public String getAttributeOne() {
return attributeOne;
}
public void setAttributeOne(String attributeOne) {
this.attributeOne = attributeOne;
}
@XmlElement(name="EntityOne")
public Entity getEntityOne() {
return entityOne;
}
public void setEntityOne(Entity entityOne) {
this.entityOne = entityOne;
}
@XmlElement(name="EntityTwo")
public Entity getEntityTwo() {
return entityTwo;
}
public void setEntityTwo(Entity entityTwo) {
this.entityTwo = entityTwo;
}
}
In the next version of MOXy (2.2) you will be able to do this via annotations.
@XmlElement(name="EntityTwo")
@XmlNullPolicy(emptyNodeRepresentsNull=true,
nullRepresentationForXml=XmlMarshalNullRepresentation.EMPTY_NODE)
public Entity getEntityTwo() {
return entityTwo;
}
You can try this now with one of the EclipseLink 2.2.0 nightly builds: