Showing posts with label JAXB. Show all posts
Showing posts with label JAXB. Show all posts

Thursday, March 8, 2012

Configuring maven to autogenerate Serializable JAXB classes

 First you need to create a bindings file:

<jxb:bindings version="1.0"
xmlns:jxb="http://java.sun.com/xml/ns/jaxb"
xmlns:xs="http://www.w3.org/2001/XMLSchema">

<jxb:globalBindings>
  <jxb:serializable uid="1"/>
</jxb:globalBindings>

</jxb:bindings>
Save this file under "src/main/resources/" of your maven module. You can name it whatever you want e.g. jaxb-bindings.xjb.

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <executions>
    <execution>
      <id>Request</id>
      <goals>
      <goal>generate</goal>
      </goals>
      <configuration>
      <schemaDirectory>src/main/resources/xsd</schemaDirectory>
      <schemaIncludes>
      <include>*/*.xsd</include>
      </schemaIncludes>
      <generatePackage>mygeneratedfiles</generatePackage>
      <generateDirectory>src/main/java</generateDirectory>
      <bindingDirectory>src/main/resources</bindingDirectory>
      <bindingIncludes>
      <bindingInclude>jaxb-bindings.xjb</bindingInclude>
      </bindingIncludes>
      </configuration>
    </execution>
  </executions>
</plugin>

Friday, August 19, 2011

Unmarshal an object using JAXB

The code below can be used to Unmarshal XML that comes in as a String value to an Object (Assuming that JAXB was used to create your classes from the Schema).

String theXMLString = " ... your XML saved as a String value ... ";
MyObject myObject = null;
try {
     //"mypackage" is the package where JAXB created the schema classes
    final JAXBContext jaxbContext = JAXBContext.newInstance("mypackage");
    final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    final ByteArrayInputStream byteStream = new        ByteArrayInputStream(theXMLString.getBytes());
    myObject = (MyObject) unmarshaller.unmarshal(byteStream);
} catch (JAXBException e) {
    System.out.println("An error has occurred: "+e.getMessage(), e);
}