JAXB By Example

Java Architecture for XML Binding makes developer's life easier .Extended markup language (XML) is standard for exchanging data in between different applications across the network and Java provides a platform for building portable applications. JAXB API provides easier and standard way of accessing XML in java application.

It is just two steps process
  1. Bind the Schema , binding xml schema to set of Java classes
  2. Unsharshaling / marshaling , XML to Java or Java to XML
Following are step by step processing of using JAXB

1. Sample department XML Schema, save in the file named dept.xsd. Put in current directory.


2. Generate Java Classes from XML Schema using xjc tool

xjc –d src/ dept.xsd

output of this command :

parsing a schema...
compiling a schema...
demo\jaxb\Customer.java
demo\jaxb\Item.java
demo\jaxb\Items.java
demo\jaxb\ObjectFactory.java
demo\jaxb\Order.java
demo\jaxb\package-info.java
demo\jaxb\package-info.java

As you see the output, it will create java class files under src/ . It creates one Class for each Element in xsd , for example Customer, Item, Items,Order.


3. Create a sample xml file corresponding to above schema


<

4. Unmarshaling above xml, parsing xml file .

package demo.jaxb.test;

import demo.jaxb.*;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;

public class UnMarshalTest {
public UnMarshalTest() {
}
static String xmlPath = "D:\\jaxb\\dept2.xml";
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance( "demo.jaxb" );
Unmarshaller u = jc.createUnmarshaller();
Order order = (Order)u.unmarshal( new FileInputStream( xmlPath ) );
BigInteger id = order.getOrderId();
String desc = order.getOrderDesc();
XMLGregorianCalendar date = order.getOrderDate();
System.out.println("Order Id = "+ id);
System.out.println("Order Desc = "+ desc);
System.out.println("Order Date = "+ date);
List items = order.getItems().getItem();
for ( Item t : items){
System.out.println("\t Item Desc = "+ t.getItemDec());
System.out.println("\t Item Quamtity = "+ t.getItemQ().toString());
}
Customer cust = order.getCustomer();
System.out.println("Customer Name = "+ cust.getCustomerName());
System.out.println("Customer Address = "+ cust.getCustomerAdd());
}
}

Output above java program will be

Order Id = 1
Order Desc = First order of its kind
Order Date = 2009-03-20
Item Desc = null
Item Quamtity = 10
Item Desc = null
Item Quamtity = 10
Item Desc = null
Item Quamtity = 10
Item Desc = null
Item Quamtity = 10
Customer Name = Yogesh
Customer Address = Hyderabad
Process exited with exit code 0.

This java class unmarshal xml document, converting xml document to java object. It creates JAXBContext passing binded java classes package ( output of binding schemea ) an gets Unmarshaller. Unmarshaller's job is to accept xml document and give java object.

5. Marshalling, Creating Xml file using java classes. Previuos steps is to convert xml document to java object, here we are going to create xml document using java claases.

package demo.jaxb.test;

import demo.jaxb.*;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.Marshaller;
import javax.xml.bind.JAXBContext;

public class MarshalTest {
public MarshalTest() {
}
static String xmlPath = "D:\\mywork\\dept3.xml";
public static void main(String[] args) throws Exception{
ObjectFactory factory = new ObjectFactory();
Order order = factory.createOrder();
order.setOrderDesc("Marshing Order");
order.setOrderId(new BigInteger("02"));
Customer cust = factory.createCustomer();
cust.setCustomerAdd("Hyderabad");
cust.setCustomerName("Yogesh");
order.setCustomer(cust);
order.setItems(new Items());
List list = order.getItems().getItem();
Item item = factory.createItem();
item.setItemDec("Item -01");
item.setItemQ(new BigInteger("20"));
list.add(item);
item = factory.createItem();
item.setItemDec("Item -02");
item.setItemQ(new BigInteger("20"));
list.add(item);
item = factory.createItem();
item.setItemDec("Item -03");
item.setItemQ(new BigInteger("20"));
list.add(item);
JAXBContext context = JAXBContext.newInstance("demo.jaxb");
Marshaller marshaller= context.createMarshaller();
marshaller.marshal(order, new FileOutputStream(xmlPath));
System.out.println("Marshaling is Done Successfuly ...");
}
}

Output XML file will be


Comments

  1. Hi yogesh, nice article, but while running application got a error of null pointer exception.
    Here below is the error
    java.lang.NullPointerException
    at MarshalTest.main(MarshalTest.java:37)

    The error in the code is
    list.add(item);

    and i changed as List list =(List)order.getItems().getItem(); for removing compile time error.

    Please help me from in this problem.

    ReplyDelete
  2. Hi
    I get the same error. When I execute my program step by step, I notice the error comes from the declaration of the context : the call of the method "newInstance()" retrieves null. JAXBContext jc is null.

    ReplyDelete

Post a Comment

Popular posts from this blog

State Design Pattern by Example

Eclipse command framework core expression: Property tester

Composite Design Pattern by example