tags:

views:

110

answers:

1

When I use the annotation:

@XmlRootElement(name="RootElement", namespace="namespace")
class RootElement {

to create xml file from java, it creates the root element as:

<ns2:RootElement xmlns:ns2="namespace">

but I wanted to create without the "ns2", like:

<RootElement xmlns="namespace">

Any idea how to fix it?

Reletad link (example I used to create the xml): http://www.java2s.com/Code/JavaAPI/javax.xml.bind.annotation/XmlRootElementname.htm

A: 

JAXB doesn't use xmlns = "namespace" in your case because xmlns = "namespace" also specifies namespace for the child elements, then your first and last elements are in default namespace (because @XmlRootElement doesn't specify namespace for the child elements). So, you need to set namespace for first and last using @XmlElement:

  @XmlElement(namespace = "namespace")
  public String getFirst() {
    return first;
  }

  ...

  @XmlElement(namespace = "namespace")
  public String getLast() {
    return last;
  }

You can also avoid the need to write namespace for every element by using package-level annotation in package-info.java:

@javax.xml.bind.annotation.XmlSchema(
    namespace = "namespace",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package foo;
axtavt