xjc: override xs:simpleType definition

2019-03-05 23:35发布

I am compiling a set of XSDs to Java classes using xjc. I would like to be able to override the data type definition for a given simple type. The XSD snippet is:

<xs:simpleType name="CPT-DateTime">
    <xs:annotation>
        <xs:appinfo>Can be specified as a integer number or as xs:dateTime</xs:appinfo>
    </xs:annotation>
    <xs:union memberTypes="xs:unsignedLong xs:dateTime"/>
</xs:simpleType>

which results (not surprisingly) in an element of the CPT-DateTime type being defined in the resulting Java class as a String, e.g.

public class CcReportTrainInitialization {
...
    @XmlElement(required = true)
    protected String time;
...
    public String getTime() {
        return time;
    }

    public void setTime(String value) {
        this.time = value;
    }
...

What I would like is for the datatype of time (in this example) to be a date-time specific type, e.g. XMLGregorianCalendar or something like that:

public class CcReportTrainInitialization {
...
    @XmlElement(required = true)
    protected XMLGregorianCalendar time;
...
    public XMLGregorianCalendar getTime() {
        return time;
    }

    public void setTime(XMLGregorianCalendar value) {
        this.time = value;
    }
...

Is this possible?

I've been experimenting with a binding file but I'm not sure it's even possible to do. Suggestions?

标签: java jaxb xsd xjc
2条回答
走好不送
2楼-- · 2019-03-06 00:16

This was actually remarkably easy once I found the right incantation; here's the bindings file:

<?xml version="1.0" encoding="UTF-8"?>
<jxb:bindings jxb:version="2.1" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <jxb:bindings node="/xs:schema" schemaLocation="../TCIP_4_0_0_Final.xsd">
    <jxb:bindings node="//xs:simpleType[@name='CPT-DateTime']">
      <jxb:class ref="javax.xml.datatype.XMLGregorianCalendar"/>
    </jxb:bindings>
  </jxb:bindings>
</jxb:bindings>
查看更多
一夜七次
3楼-- · 2019-03-06 00:24

Further options are:

I would actually argue that jaxb:class/@ref customization is not right for the simple type as this makes it a "class" type. This matters for the internal XJC model, some of the XJC plugins may handle your type incorrectly.

I think you should use jaxb:javaType here. Try:

<?xml version="1.0" encoding="UTF-8"?>
<jxb:bindings jxb:version="2.1" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tns="urn:your-target-namespace">
  <jxb:bindings node="/xs:schema" schemaLocation="../TCIP_4_0_0_Final.xsd">
    <jxb:globalBindings>
      <jxb:javaType name="javax.xml.datatype.XMLGregorianCalendar" xmlType="tns:CPT-DateTime"/>
    </jxb:globalBindings>
  </jxb:bindings>
</jxb:bindings>
查看更多
登录 后发表回答