Thursday, August 4, 2011

XML, XSD with Java and JAXB

Reference: http://www.oracle.com/technetwork/articles/javase/index-140168.html

JAXB is part of the JDK, so you shouldn't have to install anything if you already have the JDK installed.

Process Summary:
1. Make xsd file.
2. Compile it using JAXB compiler to create a java files.
3. Compile java files using a java compiler like javac.
4. Create a jar file from the .class files created.
3. Import jar file.
4. Create XML that complies with xsd.
5. Load xml into parent object from jar file.
6. Start using the object

NOTE: Compiler doesn't recognize whitespace notations in xsd file, so xml file must be careful about whitespace regardless of what the xsd indicates


STEP 0:
Make an xsd file.

Given an XML file, we use a Microsoft tool, XSD.exe to generate an XSD (XML Schema) from it.

From the command line, run:

xsd.exe myFile.xml

This will generate myFile.xsd.

STEP 1:
Using JAXB compiler example:
xjc -p myClass.jaxb myClass.xsd
This creates a directory structure of myClass/jaxb/*.java where all the java files are

STEP 2:
Compile example:
javac myClass/jaxb/*.java -d .
(NOTE: the . at the end is the output directory)

STEP 3:
Jar it example:
jar -cf myClass.jar ./myClass/jaxb/*.class
STEP 4:
First make sure to add your jar that you just compiled and import it, as well as importing javax.xml.bind.*; (or specifically what you need)
Now you ready to code. Example below:

//add package name
JAXBContext jc = JAXBContext.newInstance("myClass.jaxb");

//creating this allows a xml file to be mapped to an object
Unmarshaller unmarshaller = jc.createUnmarshaller();

//map to one of the objects that you compiled above
MyClass obj = (MyClass)
unmarshaller.unmarshal(new File( "myClass.xml"));