Understanding JAXB @XmlRootElement annotation

An SO User picture An SO User · May 16, 2013 · Viewed 66.7k times · Source

I am using the tutorial here for understanding JAXB.

When the writer comes to create the root of the document, the writer begins as below:

//This statement means that class "Bookstore.java" is the root-element of our example
@XmlRootElement(namespace = "de.vogella.xml.jaxb.model")
public class Bookstore {
       ...
}  

Although I will be manually generating my classes rather than letting Eclipse do it, I will supply an XSD with my jar file (not packed inside but rather in the folder containing jar file) so that when my application starts, it will validate whether the XML document has been tampered with.

So, in the XSD file, the targetNamespace will be de.vogella.xml.jaxb.model because it was declared above as @XmlRootElement(namespace = "de.vogella.xml.jaxb.model") ?

Answer

bdoughan picture bdoughan · May 16, 2013

I recommend using the package level @XmlSchema annotation to specify the namespace qualification for you model. A package level annotation goes in a special class called package-info that contains the exact content as shown below. That annotation will mean that all elements in your document without an explicit namespace given will use that namespace.

org/example/foo/package-info.java

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

import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;

Overriding the Namespace

  • You can override the namespace given in the @XmlSchema for all properties in a class using the @XmlType annotation.
  • You can override the namespace for a given element using the namespace property on the @XmlRootElement or @XmlElement annotation.

For More Information