Search code examples
soapjaxbwsdlschemagen

How to generate xsd from custom Java class which extends from java.util.Date by JAXB Schemagen


I have a custom java class "CustomDate1" extends java.util.Date, and I want to generate XSD file for it by Schemagen. but seems the in XSD file, the "customDate1" doesn't with the extension item, I don't know why, maybe JAXB doesn't support the class which extends Date?

Java Class:

public class CustomDate1 extends java.util.Date {

}

XSD file:

<xs:complexType name="customDate1">

<xs:sequence/>

</xs:complexType>

Joey


Solution

  • Does your domain object need to extend java.util.Date? Below is a domain class that will generate the XML schema that you are looking for ans may work better for you.

    Domain Model

    We will leverage the @XmlValue annotation on the property of type java.util.Date.

    import java.util.Date;
    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Foo {
    
        @XmlValue
        private Date value;
    
        @XmlAttribute
        private String bar;
    
    }
    

    XML Schema

    In the schema below we see there is a type that extends xsd:dateTime.

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <xs:schema version="1.0" xmlns:xs="http://www.w3.org/2001/XMLSchema">
    
      <xs:complexType name="foo">
        <xs:simpleContent>
          <xs:extension base="xs:dateTime">
            <xs:attribute name="bar" type="xs:string"/>
          </xs:extension>
        </xs:simpleContent>
      </xs:complexType>
    </xs:schema>
    

    Schema Generation Code

    The following JAXB code can be used to generate an XML schema from the JAXB model.

    import java.io.IOException;
    import javax.xml.bind.*;
    import javax.xml.transform.Result;
    import javax.xml.transform.stream.StreamResult;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            JAXBContext jc = JAXBContext.newInstance(Foo.class);
    
            jc.generateSchema(new SchemaOutputResolver() {
    
                @Override
                public Result createOutput(String namespace, String suggestedFileName)
                        throws IOException {
                    StreamResult result = new StreamResult(System.out);
                    result.setSystemId(suggestedFileName);
                    return result;
                }
    
            });
        }
    
    }