I’m trying to work with JAXB and @XmlJavaTypeAdaptor to map a Map during marshalling. The only issue I’m having is that the “item” element that is used to contain each entry in the map is given a blank namespace.
Below is an example generated XML document that shows the issue:
<format xmlns="myNamespace">
<data>
<item xmlns:ns2="myNamespace" xmlns="">
<ns2:key>Admin</ns2:key>
<ns2:value>John</ns2:value>
</item>
</data>
</format>
I would like the fragment to look like this:
<format xmlns="myNamespace">
<data>
<item>
<key>Admin</key>
<value>John</value>
</item>
</data>
</format>
I’ve simplifed the real-life example to narrow it down to just this case. Here is the class that is being marshalled:
@XmlRootElement(name = "format")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType
public final class Format {
@XmlTransient
private final Map<String, String> data = new HashMap<String, String>();
@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, String> getData() {
return data;
}
}
Here is the implementation of XmlAdapter I am using:
public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
@Override
public MapElements[] marshal(Map<String, String> stringStringMap) throws Exception {
MapElements[] mapElements = new MapElements[stringStringMap.size()];
int i = 0;
for (Map.Entry<String, String> entry: stringStringMap.entrySet()) {
mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());
}
return mapElements;
}
@Override
public Map<String, String> unmarshal(MapElements[] mapElements) throws Exception {
Map<String, String> map = new HashMap<String, String>();
for (MapElements mapElement : mapElements) {
map.put(mapElement.key, mapElement.value);
}
return map;
}
}
I set the package level information like so, this does help in that it ensures the namespace for all elements except the “item” elements have the namespace “myNamespace”:
@XmlSchema(namespace = "myNamespace", elementFormDefault = XmlNsForm.QUALIFIED)
package org.prystasj;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
I’ve tried every combination of annotation, e.g. @XmlElement(namespace=”myNamespace”), I can think of throughout and there is no chance, so I think I’m missing something conceptual (or maybe even something rather trivial).
I’m using JAXB 2.2.2.
Thanks in advance for any insight.
You could use the following for your
XmlAdapter