Danny Lipp
Danny Lipp

Reputation: 15

JAXB: What is the best way to write a method which parses Date of different formats from an XML file

So there is a way to parse Date from XML using XmlAdapter. @XmlJavaTypeAdapter(DateAdapter.class). But as far as I know this allows to parse Date of hardcoded format. Is there a way to pass desirable Date Format at runtime to the Adapter? Or any other way to parse Date of different formats from XML.

Upvotes: 1

Views: 212

Answers (1)

areus
areus

Reputation: 2947

Normally when you declare a XmlAdapter with @XmlJavaTypeAdapter, JAXB creates an instance of this adapter using the empty constructor to use it during the marshall or unmarshall operations.

But the Unmarshaller and Marshaller interfaces have a method to provide an instance of the adapter.

You could provide an alternate constructor to your DateAdapter with a parameter for the format you want to use, and also declare a DEFAULT_FORMAT. Something like this:

private String format;

public DateAdapter() {
    this(DEFAULT_FORMAT);
}

public DateAdapter(String format) {
    this.format = format;
}

And when you need to unmarshall:

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
unmarshaller.setAdapter(DateAdapter.class, new DateAdapter(someFormat));
Object o1 = unmarshaller.unmarshal(....);

unmarshaller.setAdapter(DateAdapter.class, new DateAdapter(otherFormat));
Object o2 = unmarshaller.unmarshal(....);

Upvotes: 2

Related Questions