Tag Archives: jaxb

JAXB again

the relevant stuff is mainly in javax.xml.bind package. include by default in JDK6, versions vary. tools like schemagen are not, so need to be downloaded from jaxb site.

basic example:

@XmlRootElement(name = "TimedValue")
@XmlType(propOrder = {"value", "time"})
public class TimeValue {
  private String value = null;
  private Date time = null;
  @XmlElement(name = "value")  public String getValue() {
    return value;
  }
  @XmlElement(name = "time")  public Date getTime() {
    return time;
  }
}

The result is something like

<TimedValue>
  <value>hello</value>
  <time>2008-09-29T04:49:45</time>
</TimedValue>

Note that without the “propOrder” setting the ordering of elements is random due to unpredictable reflection.

Note, I never tried to compile the above, lol, it is just an example. The given names are also a match for the class information but could be named in any other way as long as the way is XML compliant. I prefer explicit naming for understanding and evolution.

jaxb basic

OK, today I try to learn JAXB. Let’s forget for a moment that XML generation and parsing is such a trivial task that adding this type of abstraction only makes it 100 times harder to understand, debug and work with. But hey, I am not always given a real choice..

The unofficial guide seems decent (but is actually just a bunch of xml lovers hugging piles of xml file references to other xml files, with couple of pearls in there): http://jaxb.java.net/guide/

For Java to XML mapping this is brilliant: http://stephou.wordpress.com/2010/01/20/convert-java-objects-to-xml-with-jaxb/

And when someone creates a JAXB class without understanding or wanting to understand what it maps to (whooppee for the benefits of XML there)? Well, JAXB comes with schemagen that allows to generate the XML schema

http://jaxb.java.net/guide/Invoking_schemagen_programatically.html

and finally the rest of the docs including the tutorial are ok even if a bit verbose: http://jaxb.java.net/tutorial/