Customize namespace prefix when marshalling with Jaxb

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).

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 contains a utility class to marshal and unmarshal.

Trackback URL for this post:

http://www.func.nl/trackback/87
AttachmentSize
MarshalUtil.java_.txt1.85 KB

JAXB+NS2

Hello... Friend, i have generated some classes with JAXB 2.1, using the Schema (.XSD)...

Some class when i do the marshal goes OK, but classes appears the namespace NS2....
here the XML generated:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


2
INUTILIZAR
53
09
00000000123456
55
123
101
111
Falha no Sistema

But see need looks like:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


2
INUTILIZAR
53
09
00000000123456
55
123
101
111
Falha no Sistema

Please, i need

Sorry.... the xml code shows

Sorry.... the xml code shows mask here...
Please, can i get some help yours?

Thanks

Hi, We use

Hi,

We use "package-info.java" containing annotations to fix the namespaces in the XML.

please see: https://jaxb.dev.java.net/tutorial/section_6_2_3-Annotations-for-the-Sch...

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. Beside the tag style "<foo>" it is also possible to use "[foo]".