Skip to main content

Using JAXB 2.0 to persist your own classes to XML

Posted by kohsuke on February 17, 2005 at 5:15 PM PST

One of the major enhancements in the JAXB 2.0 is an ability to bind your own hand-written classes --- often called as POJOs --- to XML. And it's very easy.


For example, consider the following classes:

public class TodoList {
  private final List<Item> items = new ArrayList<Item>();
 
  ... methods ...
}

public class Item {
  private String title;
  private Kind type;
  private Calendar timestamp;
  private String description;
 
  ... methods ...
}

public enum Kind {
  PERSONAL, WORK
}

To bind these classes to XML, you need to identify what the root object to be persisted, and you need to give it an XML tag name. This is done by using the XmlRootElement annotation.

@XmlRootElement
public class TodoList {
  ...
}

Then you just compile these classes normally.

Then you create a JAXBContext object like this:

JAXBContext context = JAXBContext.newInstance(TodoList.class);

This will cause JAXB to scan the TodoList class and prepare it for binding. Because this class refers to the Item class and the Kind class, those classes will be also automatically scanned and prepared.


To write out a TodoList object, you do:

TodoList todo = ...;
context.createMarshaller().marshal(todo,System.out);

and you'll get something like:

>
 
    Dinner with the boss
    WORK
    2005-02-18T18:00:00Z
    At Chewy's
 

 
    Our 5th anniversary
    PERSONAL
    2005-02-20T18:00:00Z
    Don't forget to buy flowers!
 


You can then read this back to Java object like this:

TodoList todo = (TodoList)context.createUnmarshaller().unmarshal(System.in);

Unlike other similar technologies, JAXB allows you to control the XML representation by using annotations. For example, I don't like the element name "items", so let's change it to "todo". You can do that adding the following annotation:

public class TodoList {
  @XmlElement(name="todo")
  private final List items = new ArrayList;
  ...
}

While we are at it, why don't we change the "type" to be an attribute. To do that you use another annotation like this:

public class Item {
  @XmlAttribute
  private Kind type;
  ...
}

Now the same code would produce the following XML:

>
 
    Dinner with the boss
    2005-02-18T18:00:00Z
    At Chewy's
 

 
    Our 5th anniversary
    2005-02-20T18:00:00Z
    Don't forget to buy flowers!
 


Not only can JAXB able to persist data to XML, it can also generate a schema from this (although that code didn't make it into the currently available drop).



As usual, this is still a technology in development, so things could change before it becomes final. You can try this today by using the technology preview release of the JAXB RI 2.0. See here for how to download it.



If you have any thoughts, please let us hear it at the forum.

Related Topics >>