Monday, 22 April 2013

Jaxb: A very simple example from xsd

Converting from xml to Java objects isn't the most fun thing to do in the world, but all need to do it at some point or another.  When I need to, I use JAXB which ships with the JDK.  In this post, I'll show a basic example to illustrate how to generate the Java code from an xsd, then how to unmarshal some xml and finally how to write an adapter to format dates.

Firstly, here is a simple example of a kennel which has puppies in it.  A kennel has a list of puppies and each puppy has a name, date of birth and a timestamp of the time they arrived in the kennel (not sure why these kennel owners need a timestamp but it illustrates the point with times well later :) ).

1. Defining an xsd


The xsd definition looks like this:


2. Run the xjc compiler to generate code


To run it from the command line, I use the following command.  I am running it from src/main/java.  The  -p options tell the compiler which package to put your generated code in.

xjc ../resources/puppy/kennel.xsd -p com.ojha.jaxb.kennel.generated

This generated the package, com.ojha.jaxb.kennel.generated, which has 3 classes in it: Kennel.java, Puppy.java and an ObjectFactory.java

3. Unmarshal a sample xml file


Here is an example xml message:


The following JUnit test demonstrates how to unmarshal the xml.


Output (note that I had to generate a couple of toString() methods):


Kennel [puppy=[Puppy [puppyName=Rufus, puppyBirthday=2000-10-10, timeStamp=2013-04-12T18:30:00], Puppy [puppyName=Jasper, puppyBirthday=2012-09-12, timeStamp=2013-04-12T18:30:00]]]

I told you it would be simple.  The next couple of posts will be marginally more interesting, showing how to add adapters to do things like format the dates and how to generate enums using JAXB.








Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning...