JAXB return null instead empty string

java, jaxb

Solution

I think your XML looks more or less like this:

    <myElement></myElement>

This, unfortunately, means, that you are passing an empty string.

If you want to pass `null` you have two options:

- Do not pass this tag at all (your XML should not contain `<myElement/>` tag at all).

- Use `xsi:nil`.

If using `xsi:nil`, first you have to declare your xml element (in XSD file) as `nilable`, like this:

    <xsd:element name="myElement" nillable="true"/>

Then, to pass the `null` value inside XML do this:

    <myElement xsi:nil="true"/>

or this:

    <myElement xsi:nil="true"></myElement>

This way, JAXB knows, that you are passing `null` instead of an empty String.

Problem

How I can retrieve `null` value, when unmarshalling, if inside XML attribute value is empty ? Now I make inside my getters checking for `null` : ``` public String getLabel() { if (label.isEmpty()) { return null; } else { return label; } } ``` But may be exist some other, more elegant way? Thanks.

Original source