Wednesday, October 31, 2007 10:00 PM | rahel luethy | 2 comment(s)

simple jaxb

at work, we use the java architecture for xml binding (jaxb) for almost all of our xml input/output. our approach consists of the following steps:

  1. we start with the definition of a schema
  2. use ant to compile java classes from this schema (via xjc)
  3. have a dedicated conversion layer where we translate back and forth between the generated java classes and our business objects.

we have deliberately chosen this architecture because we need total control over xml format changes (1.), want to automate the process as much as possible (2.), and want to keep all xml-related code in a dedicated layer (3.).

this approach works really well for a big project. however, if all you need is reading a simple xml and accessing its data from your java classes (or vice-versa: dumping parts of your java objects to xml), you'd probably want to use something less heavy-weight.

what's quite cool, is that you can also use jaxb for such simple tasks. when the jaxb compiler generates java classes, it uses annotations like @XmlRootElement to map from java types to xml elements. manually annotating your java classes can thus serve as a very simple marshalling/unmarshalling strategy, which doesn't involve a schema, nor an xjc task, nor any further manual work.

here's an example of a simple java → xml → java round-trip:

the fact that jaxb 2.0 is part of java 6 makes this approach even more attractive.

2:34 PM | Anonymous Anonymous said...

have a look at xstream, even simpler

10:12 PM | Blogger Ashik Ch said...

I have a problem?? big problem!! Im writing android app which shud be able to count the number of times it had run!! but the thing is I dont wanna use any sort of external things like shared preferences, DB or external memory or internal app memory!! I just wanna save an integer in the app itself and how many times the app restarts the saved integer must not be changed unless it is changed under some condition?? is that possible??