Note. I am EclipseLink JAXB (MOXy) and a member of the JAXB 2 Expert Group (JSR-222) .
You can use the @XmlPath
extension in MOXy to do the following:
Transport
The Transport
class uses the @XmlPath
extension. Without @XmlPath
, a grouping element named mappings
will be added to the document.
package forum8403623; import java.util.*; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.eclipse.persistence.oxm.annotations.XmlPath; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Transport { @XmlJavaTypeAdapter(MappingsAdapter.class) @XmlPath(".") private Map<String, Mapping> mappings = new HashMap<String, Mapping>(); }
Mapping
package forum8403623; import javax.xml.bind.annotation.*; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(propOrder={"product", "eventName", "destination", "destinationType"}) public class Mapping { String product; String eventName; String destination; String destinationType; }
Mappingsadapter
The following class is responsible for converting to / from Map<String, Mapping>
into a view, which we will use to display XML.
package forum8403623; import java.util.*; import java.util.Map.Entry; import javax.xml.bind.annotation.adapters.XmlAdapter; public class MappingsAdapter extends XmlAdapter<MappingsAdapter.AdaptedMap, Map<String, Mapping>>{ @Override public Map<String, Mapping> unmarshal(AdaptedMap v) throws Exception { Map<String, Mapping> mappings = new HashMap<String, Mapping>(); for(Mapping mapping : v.mappings) { mappings.put(mapping.product, mapping); } return mappings; } @Override public AdaptedMap marshal(Map<String, Mapping> v) throws Exception { AdaptedMap adaptedMap = new AdaptedMap(); for(Entry<String,Mapping> entry : v.entrySet()) { adaptedMap.mappings.add(entry.getValue()); } return adaptedMap; } static class AdaptedMap { public List<Mapping> mappings = new ArrayList<Mapping>(); } }
Demo
package forum8403623; import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Transport.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum8403623/input.xml"); Transport transport = (Transport) unmarshaller.unmarshal(xml); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(transport, System.out); } }
jaxb.properties
To use MOXy as your JAXB provider, you need to add the jaxb.properties file in the same package as your domain model, with the following entry:
javax.xml.bind.context.factory = org.eclipse.persistence.jaxb.JAXBContextFactory
Additional Information