JaxB with XMLGregorianCalendar doesn't fail on invalid date

343 Views Asked by At

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?

0

There are 0 best solutions below