Java Architecture for XML Binding is the Java standard for working with XML as domain objects. It provides an easy mechanism for mapping Java classes to XML representations.
Java Architecture for XML Binding (JAXB) is the java standard (JSR-222) for working with xml as domain objects. It provides an easy to use mechanism for mapping Java classes to XML representations. An implementation is included as part of the Java SE 6 API. There are several implementations available including Metro JAXB (the reference implementation), EclipseLink MOXy, and JaxMe (retired).
JAXB and Java EE
JAXB is the standard binding layer for the following specifications:
- Java API for XML-Based Web Services (JAX-WS)
- Java API for RESTful Web Services (JAX-RS)
John Doe says "Hello World" example
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.StringReader;
public class JohnDoeSaysHello {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Person.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
String xml = "<person><name>John Doe</name></person>";
Person person = (Person) unmarshaller.unmarshal(new StringReader(xml));
System.out.println("I'm the person, "
+ person.getName()
+ ", unmarshalled from XML using a StringReader, saying, \"Hello World!\"");
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(person, System.out);
}
@XmlRootElement
public static class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Documentation
- JAXB Users Guide
- Oracle Introduction to JAXB tutorial.