This is the first time I am working this intensly with XML in Java. The code uses JAXB to generate classes and then parse. I have an XML with a date…
A class was generated by JAXB from my XML. It generated the following for the field:
@XmlElement(name = "CoverStartDate", required = true)
protected XMLGregorianCalendar coverStartDate;
In my logic I have the following
xxxx.setCoverStartDate(xmlGregorianCalendar(theDate)
There is a method xmlGregorianCalendar which looks something like this:
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(date);
return DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
My return XML that is generated, had the date with a time specified. I only want the date (year-month-day).
Any suggestions?
Thanks
Use
DatatypeFactory.newXMLGregorianCalendarDate(...)instead of simply using any of theDatatypeFactory.newXMLGregorianCalendar(...)methods.I don’t know what is
theDatein your code snippet, however if you’re working withDateobjects you can use the following.(Note that
calendar'sCalendar.ZONE_OFFSETis in milliseconds and thenewXMLGregorianCalendarDate(...)method expects the timezone value in minutes, thus it needs to be converted.)(Also note that
Calendar'smonth index is 0-based, whileXMLGregorianCalendar'smonth is 1-based.)If this isn’t working then the XML schema you’ve used to generate your JAXB classes is probably erroneous: maybe it does not specify the usage of the
xs:dateXML schema type (probably it usesxs:dateTimeinstead).Only one last advice: create your JAXB classes by hand. Then you can specify annotations like
@XmlSchemaTypeon your classes’ fields giving you much more control.