So here is a complex/retarded situation. I am writing an XSD and there happens to be a requirement where i need 2 root elements (1 at any given time)
<xs:element name="booksList">
<xs:complexType>
<xs:sequence>
<xs:element name="book" type="bookType" minOccurs="0" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
and then
<xs:element name="book" type="bookType"></xs:element>
at any given time, either of these element will be used as the root element, so an XML would look like
<bookList>
<book>
<author>XYZ</author>
</book>
</bookList>
or
<book>
<author>XYZ</author>
</book>
Both of these XML will be sent back to the user from 2 different URL’s i.e. the list will be sent from localhost/books.xml?author=XYZ and single book will be sent from localhost/book_name.xml
How can i achieve this with one xml ? I tried putting the book definition in the XSD but JAXB2.1 didn’t generate any Book class. Is there something which i am missing ?
EDIT1: BookType has been generated but BookType doesn’t have any root element.
XML SCHEMA
The XML schema below supports having the two root elements
booksListandbookthat you are looking for.GENERATED MODEL
Your JAXB (JSR-222) implementation will generate a class for the named complex type
bookType, then for thebookElementit will create an@XmlElementDeclannotation on theObjectFactoryclass.BooksList
A class with an
@XmlRootElementwas generated on this class because it corresponds to a global element with an anonymous complex type.BookType
This class was generated to correspond to the named complex types.
ObjectFactory
Global elements that correspond to named complex types have
@XmlElementDeclannotations generated on theObjectFactoryclass. This is necessary since multiple global elements could correspond to named complex types.XML
Below are the XML documents from your question.
booksList.xml
book.xml
DEMO CODE
When you unmarshal a document in which the root element corresponds to an
@XmlRootElementannotation you get an instance of the corresponding domain object. If you unmarshal a document in which the root element corresponds to an@XmlElementDeclannotation you get back an instance ofJAXBElementthat wraps a domain object corresponding to the named complex type.UPDATE
Below is a code fragment demonstrating how to wrap an instance of
BookTypein aJAXBElementso that it can be marshalled.