4

I would like to have JAXB marshal to xml where the namespaces appear ONLY in the root element and not in any others:

<myroot xmlns="http://www.mysite.com" xmlns:a="http://www.mysite.com/a" xmlns:ab="http://www.mysite.com/ab" xmlns:y="http://www.mysite.com/y">
...
</myroot>

I've tried package level @XmlSchema, but I must be doing something wrong because nothing shows up.

Here is my root element class:

@XmlRootElement(name="myroot")
@XmlAccessorType(XmlAccessType.FIELD)
public class RootElementClass
{
....
}

I also have the following package-info.java:

@XmlSchema
(
    namespace="http://www.mysite.com", 
    elementFormDefault=XmlNsForm.QUALIFIED,
    xmlns=
    {
            @XmlNs(namespaceURI = "http://www.mysite.com",    prefix = ""),
            @XmlNs(namespaceURI = "http://www.mysite.com/a",  prefix = "a"),
            @XmlNs(namespaceURI = "http://www.mysite.com/ab", prefix = "ab"),
            @XmlNs(namespaceURI = "http://www.mysite.com/y",  prefix = "y")
    }
)
package com.seastreetinc.rd.nso.jaxb;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
user3520722
  • 41
  • 1
  • 1
  • 2

1 Answers1

1

What the JAXB Spec Says (and Does Not Say)

The JAXB (JSR-222) specification does not cover where the namespace declarations occur or what the prefixes are called (see: http://blog.bdoughan.com/2011/11/jaxb-and-namespace-prefixes.html).

What the JAXB Implementations Do

The general strategy used by implementations is to figure out the minimum amount of namespaces used by the model and declare them on the root element. This could be a subset of what you have declared in the @XmlSchema annotation.


UPDATE

The NamespacePrefixMapper extension can be used to control the namespaces on the root element. See the answer linked below for a full example.

Community
  • 1
  • 1
bdoughan
  • 147,609
  • 23
  • 300
  • 400
  • Hi Blaise, thanks for your response! I should admit that I'm fairly new to namespaces with xml so I'm probably not understanding much here. Basically I have a server that needs to have certain namespaces in the root xml element for the request to work and I would like to be able to configure my Java object so that JAXB can add those namespaces during marshalling to xml. Maybe what I'm asking is not possible to do with JAXB. I'll read your blog entry that you included above and see if there's a way I can do this. – user3520722 Apr 10 '14 at 21:26