I was looking a long time on how to set the prefix for a namespace when marshalling an object to xml using JAXB. If you don’t do anything JAXB will write random namespace prefixes (like ns2, ns3).?
This is a repost of a blog item that was originally posted in the Func knowledge base by Martin Tilma on Februari 2, 2009.
First I found: https://jaxb.dev.java.net/guide/Changing_prefixes.html but with that solution you have to implement an internal abstract class NamespacePrefixMapper.
After re-reading the Javadoc of the Marshaller I found the method marshal(Object jaxbElement, XMLStreamWriter writer) and the XMLStreamWriter interface contains a method setPrefix(String prefix, String uri)
A little code example:
JAXBContext context = JAXBContext.newInstance(object.getClass()); XMLStreamWriter xmlStreamWriter = XMLOutputFactory.newInstance() .createXMLStreamWriter(writer); xmlStreamWriter.setPrefix("func", "http://www.func.nl"); Marshaller marshaller = context.createMarshaller(); marshaller.marshal(object, xmlStreamWriter);
update: I have one remaining issue, for some reason the namespace declaration isn’t written to the XML when using setPrefix. If you remove the call to setPrefix it writes the namespace declaration.
update2: After digging around I found that my project has dependency on “WoodSToX XML-processor” which specifies its own XMLOutputFactory (see the META-INF/services directory in the jar).
To fix my issue I wrote a XMLStreamWriter wrapper that calls writeNamespace(String prefix, String namespaceURI) to write the declaration.
The attachment (MarshalUtil.java_.txt) contains a utility class to marshal and unmarshal.