javaxmlxsdjaxbjaxb2

How to specify a list of complexType in XML?


I have XML specified the following:

    <xs:element name="getNewsResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="newsItem" type="tns:newsList"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>

    <xs:simpleType name="newsList">
        <xs:list itemType="tns:news"/>
    </xs:simpleType>

   <xs:complexType name="news">
        <xs:sequence>
            <xs:element name="id" type="xs:string"/>
            <xs:element name="date" type="xs:string"/>
            <xs:element name="author" type="tns:author"/>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="shortDescription" type="xs:string"/>
            <xs:element name="content" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>

I would like to have a list of the news in my response. However when I would like to create Java object with jaxb2 the xml returns the folllowing error when I run mvn clean compile -X:

org.xml.sax.SAXParseException: cos-st-restricts.1.1: The type 'newsList' is atomic, so its {base type definition}, 'tns:news', must be an atomic simple type definition or a built-in primitive datatype.

How I should change my XML to be able to compile?


Solution

  • In addition to using the built-in list types, you can create new list types by derivation from existing atomic types. You cannot create list types from existing list types, nor from complex types.

    https://www.w3.org/TR/xmlschema-0/#ListDt

    This is from one of my working XSD, a user with multiple addresses:

    <xs:complexType name="user">
        <xs:sequence>
            <xs:element name="addresses" type="tns:addressData" nillable="true" minOccurs="0" maxOccurs="unbounded"/>
    

    Note that addressData is a complexType.

    I guess this is what you need:

    <xs:element name="getNewsResponse">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="newsItems" type="tns:news" nillable="true" minOccurs="0" maxOccurs="unbounded"/>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
    
    <xs:complexType name="news">
        <xs:sequence>
            <xs:element name="id" type="xs:string"/>
            <xs:element name="date" type="xs:string"/>
            <xs:element name="author" type="tns:author"/>
            <xs:element name="title" type="xs:string"/>
            <xs:element name="shortDescription" type="xs:string"/>
            <xs:element name="content" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>