7

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.

Dan Lowe
  • 51,713
  • 20
  • 123
  • 112
user86834
  • 5,357
  • 10
  • 34
  • 47

2 Answers2

12

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

bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Thanks Blaise, but that didn't work the ATOM namespace is being set to 'ns4'. I'm using Spring MVC which uses a `Jaxb2RootElementHttpMessageConverter` I tried to extend that and add set the `com.sun.xml.internal.bind.namespacePrefixMapper ` property with my custom `NamespacePrefixMapper` but with no luck. – user86834 Jul 05 '13 at 15:30
  • I have got it working with my custom `NamespacePrefixMapper` and it is being called. Now I'm presented with another issue, by the time my custom `NamespacePrefixMapper` is called the empty prefix is already taken by the `defaultNsUri` which is hard coded in `JAXBContextImpl`. Does any one know a solution to this issue? – user86834 Jul 06 '13 at 13:05
  • Isn't `XMLConstants.DEFAULT_NS_PREFIX` preferred? – Jin Kwon Oct 04 '14 at 07:48
  • 3
    This is correct answer for the question. Still you have to define @XmlRootElement(name="name") without namespace parameter to the root element annotation. Otherwise ns1.. like namespaces will get added. – Chinthaka Senanayaka Apr 06 '17 at 06:30
1

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

Jackie
  • 25,199
  • 6
  • 33
  • 24