Online Books:
java.net on MarkMail:
Search |
||
Using JAXB 2.0 to persist your own classes to XMLPosted 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: 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
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:
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 >>
Java Web Services and XML Comments
Comments are listed in date ascending order (oldest first)
|
||
|
|