Within Java we have collections and arrays that deal with multiple objects. The collection or array has a name, but the individual objects within it do not. Because of this, the default mapping of a collection or array is just a repeating element.
Within XML, we usually like to provide a complex type element that has a sequence within it to hold the repeating elements. In other words, we want a schema that looks like the following screenshot. In this recipe, we will look at how to provide a wrapper element for our collections.
We need to know the class name of the bean and the name of the property that is a collection or array requiring a wrapper element.
<xml-element-wrapper>
element to the mapping file.In the OXM mapping file, we declare that a property requires a wrapper element in the WSDL mapping by marking it with an <xml-element-wrapper>
as follows:
<?xml version="1.0" encoding="UTF-8" ?> <xml-bindings ...> <java-types> <java-type name="soa.cookbook.QuoteRequest"> <java-attributes> <xml-element java-attribute="products" name="product"> <!-- Can provide wrapper element for arrays and collections via xml-element-wrapper element --> <xml-element-wrapper name="products"/> </xml-element> </java-attributes> </java-type> </java-types> </xml-bindings>
The <java-type> name
property is the Java class that has the property we need to provide a wrapper for. The <xml-element> java-attribute
property is the name of the Java property that needs to be wrapped, and the elements name
attribute is the name we want that XML element to have in the generated schema. The <xml-element-wrapper> name
attribute is the name we want that XML element wrapper to have in the generated schema.
If the interface has already been mapped, then it is necessary to regenerate the WSDL interface for the changes we have made to take effect. Do this by deleting the existing wire and then rewiring.
<xml-element>
is used to identify an XML element that should be generated and how it maps onto a Java bean property or class. The <xml-element-wrapper>
property causes a wrapper XML element to be a part of the generated XML Schema. Using the name
attribute allows us to control the name of the actual data element and the wrapper. We need this because often the Java property name will be a plural (such as products), and we want the actual data element to have a singular name (product) and would prefer the wrapper element to be plural (products).
The EXMMapping
project in the code samples has a sample OXM file (mappings.xml
) demonstrating this.
If we only have a single property in a bean, then there is no need for a wrapper class because the containing class provides that function.