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?
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?
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.
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.