Java HTML / XML How to - Set namespace for XML root element








Question

We would like to know how to set namespace for XML root element.

Answer

//ww w .  jav a  2 s .  c  o  m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {
  public static void main(String[] args) throws JAXBException {
    MyPerson p = new MyPerson();
    p.first = "l";
    p.last = "h";

    JAXBContext context = JAXBContext.newInstance(MyPerson.class);
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(p, System.out);
  }
}

@XmlRootElement(name = "person", namespace = "http://www.example.com/myperson")
class MyPerson {
  String first;

  String last;

  public String getFirst() {
    return first;
  }

  public void setFirst(String first) {
    this.first = first;
  }

  public String getLast() {
    return last;
  }

  public void setLast(String last) {
    this.last = last;
  }
}

The code above generates the following result.