Question

I am currently facing a problem while trying to unmarshal a date from an xml file.

Input XML snippet :

<request>
    <head>
        <title>Load data</title>
        <startDate>20130806</startDate>
        <startTime>20130807-055137</startTime>
    </head>
  <request>

The startDate and startTime elements are defined as xs:date and xs:dateTime respectively in the schema file.

After unmarshalling the xml file using JAXB, I get the value in the startDate tag in my java class as follows :

XMLGregorianCalendar xcal = request.getHead().getStartDate();
Date date =  xcal.toGregorianCalendar().getTime();
System.out.println(date);

Output : Sun Jan 01 00:00:00 IST 20130806

I debugged my code and realized that the value 20130806 is held in the year variable of XMLGregorianCalendar. I am not exactly sure why this happens but a possible reason could be that XMLGregorianCalendar needs the date to be in a sepcific format. How do I unmarshal the startDate tag so that I get the date value correctly without needing to write some Adapter and without needing to know the input date format before hand?

Was it helpful?

Solution

Your XML document does not have the xs:date and xs:dateTime information in the appropriate format. If should be the following:

<request>
    <head>
        <title>Load data</title>
        <startDate>2013-08-06</startDate>
        <startTime>2013-08-07T05:51:37</startTime>
    </head>
  <request>

If you want to use an alternate format then you will need to leverage an XmlAdapter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top