XML binding is a 2 phase process:
1. JiBX uses binding definition to define the rule how conversion wil happen and modifies byte code of the class.
2. In phase 2 JiBX runtime does marshalling and un-marshalling of java objects to populate XML to java and java 2 XML.
Algorithm
- Add following jar files to your lib directory from JiBX distribution
- bcel.jar (Byte Code Engineering Library used to change bytecode for the class)
- jibx-bind.jar (1,2 are used in phase I)
- jibx-run.jar
- jibx-extras.jar
- xpp3.jar (3,4,5 are used in phase II)
- Modify java class using binding compiler (java -jar ../lib/jibx-bind.jar binding.xml)
- Write code for marshalling and unmarshalling of java object
Example:
public void XML2Java2XML() {
try {
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
Object obj = uctx.unmarshalDocument
(new FileInputStream("customer.xml"), null);
Customer customer = (Customer)obj;
System.out.print(customer.toString());
IMarshallingContext mctx = bfact.createMarshallingContext();
mctx.setIndent(4);
mctx.marshalDocument(obj, "UTF-8", null,
new FileOutputStream("customer2.xml"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JiBXException e) {
e.printStackTrace();
}
}