Cheetah
Cheetah

Reputation: 14379

XML serialization via javax.xml.bind

I am using javax.xml.bind.* (which I believe you call JAXB) to serialize some fairly complex classes to XML.

My issue is that I seem to have to list namespaces everywhere I use a particular element. See:

@XmlRootElement(namespace="http://www.example.org/mynamespace")
public class Root {

    @XmlElement(namespace="http://www.example.org/mynamespace2")
    public Ele ele1;

    @XmlElement(namespace="http://www.example.org/mynamespace2")
    public Ele ele2;
}

public class Ele {

    @XmlAttribute
    public String attrib = "myattri";

    @XmlValue
    public String value = "value";
}

What I would prefer is for Ele to specify the namespace, so that I dont have to specify it everywhere else...

...is this possible?

Upvotes: 1

Views: 159

Answers (1)

Cheetah
Cheetah

Reputation: 14379

This is actually based the link in Blaise Doughan's comment.

Package Level Metadata

We can easily qualify all the elements through the use of the package level annotation @XmlSchema. To specify a package level annotation, create a class called package-info in the desired package (see complete source below for an example). Below we will set a default namespace and specify that by default all elements are namespace qualified.

I can add a package-info.java to the example.ele package with the following in it:

@XmlSchema( 
    namespace = "http://www.example.org/mynamespace2", 
    elementFormDefault = XmlNsForm.QUALIFIED) 
package example.ele;

and put Ele in the example.ele package.

Upvotes: 1

Related Questions