youssef ait elasri
youssef ait elasri

Reputation: 11

Generate java Array instead of Collection type with Jaxb from xsd

I want to know if anyone has already used data biding with jaxb to generate array type attributes, instead of List type, from an xsd schema, for example instead of generating List , generate Employee []

Upvotes: 1

Views: 1708

Answers (2)

negracula
negracula

Reputation: 51

In jaxb:globalBindings use the atribute collectionType="indexed". More info here "Customizing JAXB Bindings"

Upvotes: 2

Julian Dasilva
Julian Dasilva

Reputation: 76

In your XSD you would need to specify the javatype tag.

<xs:complexType name="restaurant">
    <xs:sequence>
        <xs:element name="employee" type="employee" >
            <xs:annotation>
                <xs:appinfo>
                    <jxb:javaType name="Employee[]"/>
                </xs:appinfo>
            </xs:annotation>
        </xs:element>
    </xs:sequence>
</xs:complexType>

A simple example of how to do this would be if I was receiving a message for a new restaurant order I could create a new java class for mapping the XML Elements To various Java Types based on their field name.

  @XmlAccessorType(XmlAccessType.FIELD)
  @XmlType(
    name = "restaurant",
    propOrder = {
     "name",
     "employeeArray"
   }
) 
public class RestaurantOrder {
   @XmlElement(name = "name")
   protected String name;

   @XmlElement(name = "employeeArray")
   protected Employee[] employeeArray;


   getter and setter for your employee array and name
}

Now once you have a JaxB Element you can do something similar to the following to retrieve your array By casting your JAXBElement to your newly created class.

public getArrayFromElement (JAXBElement<?> jaxbMessage) {
  RestaurantOrder order = (RestaurantOrder) jaxbMessage.getValue();
  return order.getItemArray();
}

Edit: This code assumes you have already setup a proper XSD and successfully unmarshalled your object (if you are having difficulty there then please clarify in your question). The XSD for a class setup like this would requre you've established restaurant order as a complex type in your xsd and mapped those elements there properly as well to be able to successfully cast your jaxb message to the desired class. Just a heads up I used String[] if you had an employee object you could do Arraylist or w/e you want really.

As a further note you can accept multiple complex types using JAXB by creating this kind of relationship. You can create a command pattern to parse and cast unmarshalled JAXB elements to ANY class you have mapped and this will allow you to manipulate the data to your liking while providing an extendable and scalable way to reuse your JAXB Parser that will be easy to maintain and update as needed.

Upvotes: 0

Related Questions