Monday 10 April 2017

Modifying the Namespace prefix while marshaling the JAXB object

There would be times when we want to see a meaningful name to namespace prefixes given by JAXB marshaling API. By default for any QName which does not have prefix attribute, JAXB will give prefix in this format 'ns<number>' eg: ns0, ns1 etc.

To achieve it, there is a property called MarshallerProperties.NAMESPACE_PREFIX_MAPPER ("eclipselink.namespace-prefix-mapper"); this is for JAXB reference implementation by eclipselink. If it is a different vendor, the property name will vary. For this key, we need to set a value as an instance of org.eclipse.persistence.oxm.NamespacePrefixMapper class.


  jc = JAXBContext.newInstance("com.mypackage.jaxb");
  m = jc.createMarshaller();
  m.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER,
                new NamespacePrefixMapper() {
                   // Map to store the namespace and prefixes
                    Map<String, String> namespacePrefixMap = new HashMap<>();
                        @Override
                        public String getPreferredPrefix(String namespaceuri, String suggestion, boolean requiredPrefix) {      
                            String prefix = namespacePrefixMap.get(namespaceuri);
                            if (null == prefix) {
                               prefix = "myprefix" + suggestion;
                               namespacePrefixMap.put(namespaceuri, prefix);
                             }
                             return prefix;
                        }
               });

No comments:

Post a Comment