JAXB (JSR-222) does not offer a standard way to specify the namespace prefix used.
Extension - NamespacePrefixMapper
For the JAXB reference implementations and recent versions of EclipseLink JAXB (MOXy) you can use the NamespacePrefixMapper
extension to control the namespace prefixes used.
MyNamespaceMapper
import com.sun.xml.internal.bind.marshaller.NamespacePrefixMapper;
//import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
public class MyNamespaceMapper extends NamespacePrefixMapper {
private static final String FOO_PREFIX = ""; // DEFAULT NAMESPACE
private static final String FOO_URI = "http://www.example.com/FOO";
private static final String BAR_PREFIX = "bar";
private static final String BAR_URI = "http://www.example.com/BAR";
@Override
public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
if(FOO_URI.equals(namespaceUri)) {
return FOO_PREFIX;
} else if(BAR_URI.equals(namespaceUri)) {
return BAR_PREFIX;
}
return suggestion;
}
@Override
public String[] getPreDeclaredNamespaceUris() {
return new String[] { FOO_URI, BAR_URI };
}
}
Specifying the NamespacePrefixMapper
Below is an example of how the NamespacePrefixMapper
is set on the Marshaller
.
Marshaller m = ctx.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
try {
m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", new MyNamespaceMapper());
//m.setProperty("com.sun.xml.bind.namespacePrefixMapper", new MyNamespaceMapper());
} catch(PropertyException e) {
// In case another JAXB implementation is used
}
Extension - Leveraging @XmlSchema
EclipseLink JAXB (MOXy) and recent versions of the JAXB reference implementation will use the namespace prefixes defined on the package level @XmlSchema
annotation.
@XmlSchema(
elementFormDefault=XmlNsForm.QUALIFIED,
namespace="http://www.example.com/FOO",
xmlns={
@XmlNs(prefix="", namespaceURI="http://www.example.com/FOO")
@XmlNs(prefix="bar", namespaceURI="http://www.example.com/BAR")
}
)
package blog.prefix;
import javax.xml.bind.annotation.*;
For More Information