JAXB 2.0 Hello World

For people who have played with JAXB 1.x, JAXB 2.0 has the same beahavior: it can marshall/unmarshall object from/to XML. But the syntax is completly different. It uses all kind of annotations. This blog is just about writing and executing a good old Hello World with JAXB 2.0.

First you need to download and install the binary. For the following example you will just need to put jaxb-api.jar and jaxb-impl.jar in your classpath.

The following code represents a HelloWorld class with two attributes. The main method creates a HelloWorld object, sets some values, marshalles it to the hello.xml file, displays the xml representation, unmarshalles the xml file into a HelloWord and displays the toString method :

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.File;
import java.io.FileOutputStream;

@XmlRootElement
public class HelloWorld {

  private String hello;
  private Integer world;

  public String getHello() {
    return hello;
  }

  public void setHello(String hello) {
    this.hello = hello;
  }

  public Integer getWorld() {
    return world;
  }

  public void setWorld(Integer world) {
    this.world = world;
  }

  public String toString() {
    return hello   "-"   world;
  }

  public static void main(String[] args) throws Exception {

    // Set up file and JAXB context
    final File file = new File("hello.xml");
    JAXBContext context = JAXBContext.newInstance(HelloWorld.class);
    
    // Creates a HelloWorld object
    HelloWorld hw = new HelloWorld();
    hw.setHello("Hello !!!");
    hw.setWorld(1234);
    
    // From a HelloWorld object creates a hello.xml file
    Marshaller m = context.createMarshaller();
    m.marshal(hw, new FileOutputStream(file));
    m.marshal(hw, System.out);

    // From the hello.xml file creates a HelloWorld object
    Unmarshaller um = context.createUnmarshaller();
    HelloWorld hw2 = (HelloWorld) um.unmarshal(file);
    System.out.println("\n\n" + hw2);

  }
}

Categories: Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s