Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default namespace using JAXB

I have a ATOM-XML representation of my data that is returned via a Spring MVC web service. I'm using JAXB to do the serialization, I have a number of namespaces but I want the default namespace set to Atom with no prefix. Here is what I have so far in package-info.java but the atom prefix is being set to ns3.

@XmlSchema(namespace = com.mycomponay.foo.ATOM_NAMESPACE,
xmlns = { 
    @XmlNs(prefix = "foo", namespaceURI = com.mycomponay.foo.NAMESPACE_FOO),
}, elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.mycompany.web;

import javax.xml.bind.annotation.XmlNs;

Also I noticed the namespaces display in chrome but not in Firefox.

like image 245
user86834 Avatar asked Jul 04 '13 21:07

user86834


People also ask

How do I set namespace prefix in JAXB?

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.

How do I remove namespace prefix JAXB?

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


2 Answers

Try adding an @XmlNs annotation with prefix "" for the namespace you want to appear as the default.

@XmlSchema(
    namespace = com.mycompany.foo.ATOM_NAMESPACE,
    xmlns = { 
        @XmlNs(prefix = "", namespaceURI = com.mycompany.foo.ATOM_NAMESPACE),
        @XmlNs(prefix = "foo", namespaceURI = com.mycompany.foo.NAMESPACE_FOO)
    }, 
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.mycompany.web;

import javax.xml.bind.annotation.*;

Note:

The namespaces specified in the @XmlSchema annotation are meant to affect the generation of the XML Schema and are not guaranteed to be used when a object model is marshalled to XML. However EclipseLink JAXB (MOXy) and recent versions of the JAXB reference implementation will use them whenever possible.

For More Information

  • http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html
like image 116
bdoughan Avatar answered Sep 25 '22 16:09

bdoughan


if you are using separate class for XML element, annotate it with namespace="", would work.

like image 24
engineer Avatar answered Sep 22 '22 16:09

engineer