User Tools

Site Tools


jaxb

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 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

<dependency>
  <groupId>javax.xml</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.1</version>
</dependency>

Create classes from XSD file during build

<build>
  <plugins>
    <plugin>
      <groupId>org.jvnet.jaxb2.maven2</groupId>
      <artifactId>maven-jaxb2-plugin</artifactId>
      <executions>
        <execution>
          <goals>
            <goal>generate</goal>
          </goals>
        </execution>
      </executions>
    </plugin>
  </plugins>
</build>

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:

jaxb.txt · Last modified: 2012/08/26 17:23 by hkoller