The **Java Architecture for XML Binding** (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects.
====== JAXB with Maven ======
JAXB can be combined with Maven using the [[http://java.net/projects/maven-jaxb2-plugin/pages/Home | maven-jaxb2-plugin ]]. The Maven build can then use the JAXB binding compiler (**xjc**) to generate a package of Java classes from an XML schema.
===== Configuring pom.xml =====
** Add dependency to jaxb-api **
javax.xml
jaxb-api
2.1
** Create classes from XSD file during build **
org.jvnet.jaxb2.maven2
maven-jaxb2-plugin
generate
xjc per default searches for XSD files in the directory //src/main/resources// and generates the classes to //target/generated-sources/xjc///
====== Marshalling ======
// create a request object
Request request = new Request(); // Request is defined in the XML Schema, classes generated with xjc
request.setId(123); // set more parameters if required
// create XML
ByteArrayOutputStream requestXML = new ByteArrayOutputStream();
JAXB.marshal(request, requestXML);
System.out.println(requestXML);
====== Unmarshaling ======
Assume you have an XML File which contains a Result object. (and the corresponding java classes have been generated from an XML Schema using xjc)
StreamSource s = new StreamSource(new FileInputStream("file.xml"));
JAXBContext jaxbContext = JAXBContext.newInstance("my.name.space");
Unmarshaller u = jaxbContext.createUnmarshaller();
Result r = u.unmarshal(s, Result.class).getValue();
**Note:**
For some reason xjc does not always generate the correct **@RootElement** annotations in the class definitions. As a result the unmarshaller might complain about a missing namespace when we try to unmarshal like this:
Result r = (Result) u.unmarshal(s)
To fix this we need to explicitly tell the unmarshaller which class it should unmarshal by passing it the **//Result.class//** as parameter. For details see:
* http://weblogs.java.net/blog/kohsuke/archive/2006/03/why_does_jaxb_p.html
* http://stackoverflow.com/questions/819720/no-xmlrootelement-generated-by-jaxb
* http://magicmonster.com/kb/prg/java/ws/jaxb/expected_elements_are_none_xjc_fix.html