Detecting Empty XML Elements with JAXB

I use JAXB in conjunction with Apache CXF for web services. One requirement for the data model is to allow data fields to be “cleared”. This is done by entering no value in the XML. Data elements of the model can also be left out completely. This means that the value should not be set and is very different from a clear. Consider a JAXB class with one string field, one number field and one date field.

The previous XML indicates that the string, number and date values should all be cleared. The actual values you would get in the data model are as follows:

If no XML was passed in, the following would be the resulting values in the data model:

For string values, you can tell if the user intends to clear the value by checking if the value is empty string. The problem comes in when you look at the number and date fields. You get NULL if the XML element is present or not. This makes it impossible to tell the difference between no XML being specified and an empty XML element.

The solution I came up with was to use a special number and date to denote a clearable value. I wanted to pick numbers that should never occur in the data model so I chose the following:

In JAXB, I set these values to the “default value” in the XML schema. This means that if the user types in the XML element by itself with no text value, it should be treated as the default value. If the user leaves the element out, according the the schema spec, the default value should not be used. This is exactly the behaviour I want for the “clearable” fields.

On the data model class, I added the annotations on dates and numbers respectively (actually I used a constant):

Now, if you have the original XML example:

You will get the following values in the data model:

Now we can easily differentiate between an empty XML element and leaving out the element altogether.