users@jaxb.java.net

Supporting Maps

From: Brian Pontarelli <brian_at_pontarelli.com>
Date: Sun, 13 Feb 2005 14:00:59 -0600

I had an idea for JAXB customization. Currently elements that contain
multiple sub-elements, those elements are stored in a List<Type> (Type
being the type of the sub-element). In some cases, the sub-elmenets will
have attributes that uniquely identify them from their siblings. Here's
a snippet:

<shoppingCart>
  <item id="42098209823" cost="40.50"/>
  <item id="20983098420" cost="75.00"/>
</shoppingCart>

If this is the case and the schema designer wishes to access these items
as a Map they currently only have the option of sub-classes the JAXB
generated class to provide a Map method. Could this be added into the
customization sechema? I was thinking something like this:

<jaxb:property name="item" collectionType="java.util.HashMap"
keyAttribute="id"/>

The methods would then look like this:

public Map<String, Item> getItem() { ... }

public void setItem(Map<String, Item>) { ... }

Using a HashMap would loose the ordering of elements, but using a
LinkedHashMap would retain the order they appear in the XML document.
You could also explode the concept out so that duplicates could be
stored correctly using a structure like this:

Map<String, List<Item>>

This could be controlled via a flag in the customization like this:

<jaxb:property name="item" collectionType="java.util.HashMap"
keyAttribute="id" retainDuplicates="true"/>

What do you all think?

- brian