Search code examples
datetimejaxbxml-parsingjaxb2xjc

How to generate class with field of type Date from xs:string element with JAXB


I have xsd schema file which I can't change.
Here is an excerpt that makes my problem:

<xs:element name="Event" maxOccurs="unbounded">
    <xs:complexType>
        <xs:all>
            <xs:element name="EventDate" type="xs:string" minOccurs="0">
...

Here is an example of string data I get for EventDate:

2012-05-30T12:30:00 CEST

I'm compiling with xjc and I get Event class with String field.
Is there a way to get Event class with some kind of Date field?
I guess I should write some kind of adapter and that's ok but I don't know how to tell xjc to use it only on EventDate element.


Solution

  • I'm compiling with:

    xjc -b temp.xml schema.xsd
    

    This is part of temp.xml:

        <jaxb:bindings node="//xs:element[@name='EventDate']">
            <jaxb:property>
                <jaxb:baseType>
                    <javaType name="java.util.Date"
                        parseMethod="com.mydomain.adapters.DateAdapter.parseDate"
                        printMethod="com.mydomain.adapters.DateAdapter.printDate"
                    />
                </jaxb:baseType>
            </jaxb:property>
        </jaxb:bindings>
    

    And here is part of com.mydomain.adapters.DateAdapter class:

    private static final DateFormatter df = new DateFormatter("yyyy-MM-dd'T'HH:mm:ss z");
    public static Date parseDate(String v) {
        Date date = null;
        try {
            date = df.parse(v, Locale.getDefault());
        } catch (ParseException e) {
            throw new MyException("Could not parse date:" + v);
        }
        return date;
    }
    
    public static String printDate(Date v) {
        return df.print(v, Locale.getDefault());
    }