Browse DevX
Sign up for e-mail newsletters from DevX


Generate XML Mapping Code with JAXB : Page 2

If you write any DOM or SAX code, you need to learn Java Architecture for XML Binding (JAXB). It rapidly generates XML mapping code for you, saving time and effort, and reducing both costs and risks.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

A Working JAXB Example
First things first: download JAXB from java.sun.com, and since it relies on other XML libraries, downloading their whole XML package is perhaps the easiest way to go. As of the writing of this article, the latest pack is Summer 02. Set up the environment as per the instructions or nothing will work. The source code for the example, the schema you'll use, and a document conforming to it are all available to download in this article.

The example document I use is Shakespeare's "A Midsummer Night's Dream", which I found on the Web in XML format. I made a few small changes to slightly simplify the structure and emphasize issues I wish to focus on, and I generated a W3C Schema using the latest version of Altovira's excellent XML Spy Enterprise. (Figure 1 shows the fairly simple schema in the XML Spy diagramming format.)

Figure 1: The Play Schema

The play schema shows that a play must contain six elements. One element is an act, which must itself contain many scenes, and scenes consist of many intermingled stage directions and speeches. Speeches contain many speakers, lines, and stage directions, again in no predictable order.

Figure 2 shows a simple play-viewer application that I put together to demonstrate the principles of processing with JAXB. Writing this would have been a lot easier had I used Tomcat and an HTML GUI, but I didn't want to "complexify" things.

Figure 2: Play Viewer

How long would it take you to write this using SAX or DOM? The GUI is quite straight forward, but the mapping code may take you a while. Maybe two days? I did the entire thing in half a day using JAXB, and most of that was spent playing with the enigmatic Swing interface, trying to make it look a bit prettier for the screenshot. I created the mapping code in about three seconds. The panel on the left contains a standard tree and the one on the right contains a subclass of Jlabel, which I altered to implement the Scrollable interface and to hold off displaying its contents until the application gives it permission.

Thanks for your registration, follow us on our social networks to keep up-to-date