1

We are using JAXB to parse a LocalDate object into XML. Even though the XSD specifies the target field to be xsd:date the Marshaller writes a xsd:datetime string into the Stream.

What is the best way to correct this?

Christoph Grimmer
  • 4,210
  • 4
  • 40
  • 64
  • 2
    Did you start from a schema or Java classes? Can you share what the date property looks like and how it is currently annotated and the corresponding element definition from the schema. – bdoughan Mar 05 '15 at 11:29
  • 1
    Hi Blaise, your blog entry http://blog.bdoughan.com/2011/01/jaxb-and-datetime-properties.html actually got me on the right track. Thanks for that :-) – Christoph Grimmer Mar 05 '15 at 13:30

2 Answers2

3

Ok, we found the problem. In the XSD the element was defined like this

<xs:element name="validto" type="ValidityDateType"/>
<xs:simpleType name="ValidityDateType">
    <xs:restriction base="xs:date"/>
</xs:simpleType>

As far as I know Altova XMLSpy is responsible for this beautiful piece of XML...

Apparently the jaxb-maven-plugin is not able to infer the correct type (even though it creates the member as XmlGregorianCalendar). As a result the member in the generated Type class was not annotated with

@XmlSchemaType(name = "date")

So on the way back to XML the JAXB Marshaller could not know whether to create a date or dateTime string representation of the XmlGregorianCalendar. We simplified the XSD and validto is now directly of type "xs:date". An guess what? JAXB now works as intended.

Christoph Grimmer
  • 4,210
  • 4
  • 40
  • 64
0

You could use a JAXB adapter:

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class DateAdapter extends XmlAdapter<String, LocalDate>
{

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T");

@Override
public Date unmarshal(String v) throws Exception
{
    return dateFormat.parse(v);
}

@Override
public String marshal(LocalDate v) throws Exception
{
    return dateFormat.format(v);
}

Then, the "date" format will be called when marshalling and you will have a "date" in the output.

Victor
  • 2,450
  • 2
  • 23
  • 54
  • Hi Victor, thank you. I found a very similar answer at this question http://stackoverflow.com/questions/13568543/how-do-you-specify-the-date-format-used-when-jaxb-marshals-xsddatetime and this seems like a quite complicated way to do it :-( – Christoph Grimmer Mar 05 '15 at 10:39
  • Well, in my opinion is not very complicated, just a bit cumbersome, because you have to change manually your XSD-generated POJOs and add the @XmlJavaTypeAdapter(DateAdapter.class) annotation. It works, though :) – Victor Mar 05 '15 at 10:51
  • The problem with this is that the XSD is not yet stable. I will have to annotate the POJO manually every time it changes. Thats why I'm looking for a way to tell JAXB to write date data into a date field which IMO is what it should do in the first place. – Christoph Grimmer Mar 05 '15 at 10:54