Tag Archives: XML

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.


<string-value/>
<number-value/>
<date-value/>

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:


string-value: "" (empty string)
number-value: NULL
date-value: NULL

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


string-value: NULL
number-value: NULL
date-value: NULL

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:


Date: Epoch, 1970-01-01T00:00:00.0-00:00
Number: Integer.MIN_VALUE, -2147483648

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):


@XmlElement(defaultValue="1970-01-01T00:00:00.0-00:00")
@XmlElement(defaultValue="-2147483648")

Now, if you have the original XML example:


<string-value/>
<number-value/>
<date-value/>

You will get the following values in the data model:


string-value: "" (empty string)
number-value: -2147483648
date-value: new Date(0) (1970-01-01T00:00:00.0-00:00)

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