|
Java™ by example!
|
|
|
How do I use JAXB?
JAXB allows for a mapping between Java objects and XML files. The following example goes through a couple steps so you get a feel of this powerful library. Download the early-access implementation from http://java.sun.com/xml/jaxb, and add the JAR files to your classpath. First, write a DTD that describes your object. customer.dtd (!!remove the space between the ? and xml) :
To map this description of a customer to an object (tree), you can invoke the schema to java compiler:
output:
Two files have been created that are the equivalent of the DTD. You can further customize the mapping by creating a .xjs file. For example, in the following customer.xjs file, it is specified that the attribute custid is mapped onto an int in the Java object (the default was a String). Also, the classes are to be placed in the package com.esus.jaxbtest. customer.xjs (!!remove the space between ? and xml):
Now run the conversion utility again, but specify your customized mapping:
output is now:
Now, let's test the mapping and create an XML file data.xml that describes one customer. data.xml (!!remove the space between ? and xml):
java Main:
Notice that the conversion halts because data.xml does not contain the tag addline2 while it was required in the original DTD customer.dtd. Let's make addline2 optional, and regenerate. customer.dtd (!!remove the space between ? and xml):
Notice now that the unmarshalling fails because our customer record does not contain the required custid attribute. Add it! data.xml (!!remove the space between ? and xml):
Now run again:
To go the other way: Main.java:
After executing this program, the following file out.xml will be created:
Further Information
Author of answer: Joris Van den Bogaert
Comments to this answer are only viewable by members. Login or become a member!
|
|
|
|
|