If you are using the default JAXB implementation provided with Java 6 or later, you can configure the namespace prefixes by extending the NamespacePrefixMapper and setting a property to tell the marshaller to use your extension.
You can use the NamespacePrefixMapper extension to control the namespace prefixes for your use case. The same extension is supported by both the JAXB reference implementation and EclipseLink JAXB (MOXy).
In JAXB, marshalling involves parsing an XML content object tree and writing out an XML document that is an accurate representation of the original XML document, and is valid with respect the source schema. JAXB can marshal XML data to XML documents, SAX content handlers, and DOM nodes.
http://hwellmann.blogspot.com/2011/03/jaxb-marshalling-with-custom-namespace.html
This shows how to do it.
Another: http://www.systemmobile.com/?p=280
Key bits in case that link dies too:
the NamespacePrefixMapper class, found in the com.sun.xml.bind.marshaller package. The abstract class has one method to implement:
public abstract String getPreferredPrefix(
String namespaceUri,
String suggestion,
boolean requirePrefix);
then
Marshaller marshaller =
jaxbContext.createMarshaller();
marshaller.setProperty(”com.sun.xml.bind.namespacePrefixMapper”,
new MyNamespacePrefixMapper());
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.
I tested that in Java SE6 and it requires a small change compared to the solution for Java SE 5 (as described above):
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
m.setProperty("com.sun.xml.internal.bind.namespacePrefixMapper", mapper);
So the third property from above contains the additional .internal.
in the package name compared to the Java SE5 version.
What I did not find out yet is how to tell the Marshaller which namespace URI becomes the default namespace (""). If I override the method getPreferredPrefix() and return an empty string, the Marshaller has issues with writing attributes of the default namespace (in this case it creates a new namespace called ns1)
I had the same question. In package-info.java
(if you don't have it, you can just manually create it) add the xmlns
part:
@javax.xml.bind.annotation.XmlSchema(xmlns = {
@javax.xml.bind.annotation.XmlNs(namespaceURI = "urn:just:attributes", prefix = "thirdpartyns") },
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With