6

I have a JAXB class like this:

public class Game {
    private Date startTime;

    @XmlElement
    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }
}

which results in an .xsd where startTime has type xsd:datetime. I want it to be xsd:time. xsd:time maps to XmlGregorianCalendar, but the reverse mapping maps to xsd:anySimpleType which isn't very helpful.

I've tried various arguments to @XmlElement(type=...) to no avail. Any pointers would be greatly appreciated.

If it makes a difference, this is a type used by JAX-WS.

Draemon
  • 33,955
  • 16
  • 77
  • 104
  • I'm not clear if you're trying to generate Java from XSD, or generate XSD from java? – skaffman Nov 11 '09 at 12:03
  • @skaffman: xsd from java – Draemon Nov 11 '09 at 12:44
  • If you want to keep `startTime` as `Date` type, have a look at this [post](http://stackoverflow.com/questions/2519432/jaxb-unmarshal-timestamp). It defines a mapping between `Date` and `String`, that is used to serialize the actual `Date` type. – kon Jan 24 '13 at 09:55

1 Answers1

6

If you are generating the schema from the Java classes here is what you should change:

public class Game {
    private XMLGregorianCalendar startTime;

    @XmlElement
    @XmlSchemaType(name = "time")
    public XMLGregorianCalendar getStartTimeForSchema() {
      return startTime;
    }

    public void setStartTimeForSchema(XMLGregorianCalendar startTime) {
      this.startTime = startTime;
    }

    @XmlTransient
    public Date getStartTime() {
      return startTime.toGregorianCalendar().getTime();
    }

    @XmlTransient
    public void setStartTime(Date startTime) {
    GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
      gc.setTime(startTime);
      DatatypeFactory dataTypeFactory = null;
      try {
        dataTypeFactory = DatatypeFactory.newInstance();
      } catch (DatatypeConfigurationException ex) {
        // log
      }
      this.startTime = dataTypeFactory.newXMLGregorianCalendar(gc);
    }
}
David Rabinowitz
  • 29,904
  • 14
  • 93
  • 125
  • Looking good. I'd completely missed XmlSchemaType (perhaps since it's not mentioned in the jax-ws docs on annotations: https://jax-ws.dev.java.net/jax-ws-ea3/docs/annotations.html My only problem now is to convert a `Date` to an `XMLGregorianCalendar` - not so easy considering how pathologically insane Java's Date handling is. – Draemon Nov 11 '09 at 12:46
  • Thanks for all your help. This would be better for the first line of setStartTime(): Calendar gc = GregorianCalendar.getInstance(); – Draemon Nov 11 '09 at 16:59