Customizing JAXB’s Namespace Prefixes
At a recent event in Denver, some of our integration partners complained about the namespace prefixes in the XML we generated. By default, JAXB creates simple prefixes like “ns1″, “ns2″ and so on. I’m not sure it matters unless you’re processing XML using some archaic means, but keeping partners happy is usually a good idea, so I turned to the JAXB API.
JAXB makes prefix customization pretty easy through the NamespacePrefixMapper class, found in the com.sun.xml.bind.marshaller package. The abstract class has one method to implement:
From here, it’s a simple matter of returning the prefix you want for a given namespace, then telling your JAXBContext about your implementation:
If you’re also using javax.xml.xpath.XPath, your NamespacePrefixMapper can also implement javax.xml.namespace.NamespaceContext, centralizing your namespace customization in a single class.