1

Today we faced a very unexpected behaviour when we tried to read a XML with JaxB. In our model we had a field of type XMLGregorianCalendar. In our XML we got a wrong date format. We expected to see an exception but unmashalling was successful just the field was null.

Here's the corresponding unit test:

public class JaxBUnknownDateFormatTest {

  @XmlRootElement(name = "MyXml")
  static class MyXml {
    @XmlElement
    @XmlSchemaType(name = "date")
    public XMLGregorianCalendar some_date;
  }

  @Test
  public void wrong_date_format() throws Exception {
    Unmarshaller unmarshaller = JAXBContext.newInstance(MyXml.class).createUnmarshaller();

    // correct date format
    String xml = "<MyXml>    <some_date>2021-12-31</some_date>   </MyXml>";
    MyXml myXml = (MyXml) unmarshaller.unmarshal(new StringReader(xml));
    Assert.assertNotNull(myXml.some_date);

    // wrong date format ... no failure just null
    String xml2 = "<MyXml>    <some_date>31.12.2021</some_date>   </MyXml>";
    MyXml myXml2 = (MyXml) unmarshaller.unmarshal(new StringReader(xml2));
    Assert.assertNotNull(myXml2.some_date); // <-- fails
  }
}

Is there any possibility to configure JaxB that it fails if field can not be parsed as date?

Marcel
  • 4,054
  • 5
  • 36
  • 50
  • Related (possible duplicate): [How do you specify the date format used when JAXB marshals xsd:dateTime?](https://stackoverflow.com/q/13568543/12567365). Do any of the answers there help? They discuss `XMLGregorianCalendar` specifically. – andrewJames Apr 26 '22 at 13:19
  • By the way, for a date-only value, you should be using `LocalDate` rather than `XMLGregorianCalendar`. – Basil Bourque Apr 26 '22 at 14:42

0 Answers0