javaxmljaxbmaven-jaxb2-plugin

Java class to XSD


Could someone please tell me what XSD matches this Java class?

public class MyClass {

    private List<String> list1;

    private List<String> list2;

    private XMLGregorianCalendar date;

    // getters and setters
}

I've tried the following, but I'm receiving an One of :attribute, :attributeGroup, :anyAttribute is expected error:

<xs:element name="myClass">
  <xs:complexType>
    <xs:sequence minOccurs="0" maxOccurs="unbounded">
      <xs:element name="list1" type="xs:string"/>
    </xs:sequence>
    <xs:sequence minOccurs="0" maxOccurs="unbounded">
      <xs:element name="list2" type="xs:string"/>
    </xs:sequence>
    <xs:element name="date" nillable="true" type="xs:dateTime"/>
  </xs:complexType>
</xs:element>

So it seems I'm not using the <xs:sequence> tag correctly. Could someone please shed some light? (I'm far from being an expert in XML-related stuff)...

I'm using Spring Boot 1.4.4.RELEASE version with Java 7.


Solution

  • The xs:sequence within a xs:complexType defines a specific order in which an elements children must occur. To create a list of elements you simply use the minOccurs and maxOccurs directly on the xs:element tag you want repeated, as follows:

    <xs:element name="myClass">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="list1" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
          <xs:element name="list2" type="xs:string" minOccurs="0" maxOccurs="unbounded"/>
          <xs:element name="date" nillable="true" type="xs:dateTime"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
    

    This should create the class you expect and require XML such as the following (order of tags matter):

    <myClass>
      <list1>a</list1>
      <list1>b</list1>
      <list2>y</list2>
      <list2>z</list2>
      <date>2019-06-26T00:00:00.0000000Z</date>
    </myClass>
    

    Placing minOccurs and maxOccurs on the xs:sequence tag requires the entire sequence of elements to be repeated.