Showing posts with label JIBX. Show all posts
Showing posts with label JIBX. Show all posts

Thursday, October 2, 2008

JIBX -- Step by Step Tutorial

To install JiBX, just download the distribution zip file and unpack it. This will create a jibx directory that contains the distribution files, including a complete copy of this documentation. 


I installed it in C:\JIBX

Create a directory example23 in C:\jibx\tutorial\

Create a file Customer.java with following contents:

package example23;

public class Customer {
    public Person person;
    public String street;
    public String city;
    public String state;
    public Integer zip;
    public String phone;
}

Create a file Person.java with following contents:

package example23;

public class Person {
    public int customerNumber;
    public String firstName;
    public String lastName;
}

Create a file binding.xml with following contents:



Go to C:\jibx\tutorial from cmd prompt and execute following command:
javac example23/*.java

Now execute 
java -jar C:\jibx\lib\jibx-bind.jar example23\binding.xml

Now go to example23 directory and create CustomerManager.java wih contents

package example23;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;

public class CustomerManager {
public CustomerManager()
{
try {
IBindingFactory bfact = BindingDirectory.getFactory(Customer.class);
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
   
Object obj = uctx.unmarshalDocument
   (new FileInputStream("C:/jibx/tutorial/example23/customer.xml"), null);
Customer customer = (Customer)obj;
System.out.print(customer.street+", "+customer.city);
IMarshallingContext mctx = bfact.createMarshallingContext();
   mctx.setIndent(4);
   mctx.marshalDocument(obj, "UTF-8", null,
       new FileOutputStream("C:/jibx/tutorial/example23/customer2.xml"));
   
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JiBXException e) { 
e.printStackTrace();
}
}
public static void main(String[] args) {
new CustomerManager();
}

}


Create a customer.xml file with following contents:







Now execute CustomerManager.java and see JIBX in action :) 

Thanks note to techBlog.

But the process was not clear so i wrote this blog with things crystal clear.