Thursday, developer meeting day at MINDSEYE. We all put our feet up on the conference table, sip on a Mike’s or a Guinness and ‘interface’. Today Maia did an impromptu presentation on JAXB, a Java technology from Sun “…automates the mapping between XML documents and Java objects.” Sounds pretty boring doesn’t it? Stop reading then.
So I’ve written a couple apps that use Java and alot of applications that use XML. IMNSHO, the most tedious programming I’ve ever done is the work I’ve done parsing, validating, and hacking at XML. XML is a boon to developers, but who really wants to write ‘lElements.item(0).text’ over and over again? Not many people I know. Anyway, JAXB. JAXB takes the tedium out of using XML and for that reason alone is a great tool. In short, you use JAXB to:
- unmarshal XML content into a Java representation
- access, update and validate the Java representation against schema constraint
- marshal the Java representation of the XML content into XML content
In non-geek, that means that you can hand an XML document to a Java system that uses JAXB, the developer writes about 3 lines of code to transform that XML document into a Java object, the developer can then pass that Java object around in his or her system, and then at some point in time easily transform that Java object back into XML. No messing with childNode() or GetElementsByTagName(). Beautiful. But it gets better. JAXB creates Java objects for you that represent the XML document you pass in. These Java objects are created by JAXB with accessor methods so that you can modify the contents of the XML document…without knowing any XML syntax. So if you had an xml document that looked like this:
<?xml version=”1.0″?>
<application>
<caching bCache=”false” objectttl=”0″>
</application>
you’d get a Java class called ‘caching’ with getters and setters for the bCache and objectttl properties. You could pass in the above XML document and modify the settings in 5 lines of code (pseudo code, not tested or compiled, use at your own risk):
JAXBContext jc = JAXBContext.newInstance( “primer.po” );
Unmarshaller u = jc.createUnmarshaller();
caching c = (caching)u.unmarshal( new FileInputStream( “config.xml” ) );
c.setBCache=”true”;
c.setObjectttl=”36000″;
not so bad is it? For the sake of getting you hooked, I neglected to mention the fact that for every type of XML document that you want to use, you first have to create an XML Schema Document, but hey, you’re lazy right? That’s what makes you a good programmer.
Related links:
Binding XML Schema to Java Classes with JAXB: java.sun.com tutorial
JAXB FAQ: [link]
The JAXB API: [xml.com article]
JAXB Mailing List [java.sun.com]
Developing with JAXB and Ant: [onjava.com]
Generate XML Mapping Code with JAXB: [devx.com]
Brett McLaughlin on JAXB: [newinstance.com], note: adding Brett to blogroll. Brett wrote Java & XML: Solutions to Real-World Problems, Building Java Enterprise Applications Vol. II: Web Applications, and Java and XML Data Binding.