Monday, December 5, 2011

Generate XSD with Trang and Parsing XML with JAXB

The JAXB binding compiler helps us to generate Java classes from a given XSD. It generates a collection of Java classes based on the provided XSD.
First you need to have the xml file to be parsed from JAXB.
The sample i am going to use is info.xml and it is as follows:

Trang can be used to infer an XSD from an XML document. The steps are as follows:

1. Download the Trang distribution zip file and extract it to a location in your machine.
2. Go to the root folder of Trang in the command prompt and type the command to generate XSD from the given XML file as mentioned below:

java -jar trang.jar info.xml info.xsd

(Note: I have copied the sample xml file to the Trang root directory and i am expeting the output xsd file to be created in the same place)

The generated XSD is as follows:

Now in order to parse the info.xml file we can use JAXB to input the generated info.xsd and generate the classes.

The command line tool "xjc" can be used to run the JAXB compiler. The command to generate the classes is as follows:

xjc info.xsd -p com.pu.jaxb.sample

The output of the above command will be a folder structure "com.pu.jaxb.sample" with 4 classes:
ObjectFactory.java
Education.java
Info.java
Institute.java

In order to Unmarshall the info.xml file i have written the code segment depicted below:


Now with the use of info instance you can access all the values defined in XML file.