Sample on JAXB using Eclipse

Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations.

JAXB provides two main features:

1. The ability to marshal Java objects into XML

2. To unmarshal  XML back into Java objects.

In other words, JAXB allows storing and retrieving data in memory in any XML format, without the need to implement a specific set of XML loading and saving routines for the program’s class structure. It is similar to xsd.exe and xmlserializers in .Net Framework.

JAXB is particularly useful when the specification is complex and changing. In such a case, regularly changing the XML Schema definitions to keep them synchronised with the Java definitions can be time consuming and error prone.

Follow the steps to configure and Test JXB Sample project in Eclipse.

1. Install Eclipse plug-in for JXB2.0 https://jaxb-workshop.dev.java.net/plugins/eclipse/xjc-plugin.html
or click on the link to download jaxb-xjc(rename the “docx” extension  2 “jar”)

2. Once download extract the Zip file and copy the folder “org.jvnet.jaxbw.eclipse_1.0.0” into the home directory of Eclipse > plug-in

3. Re-start the Eclipse, if the plug-in doesn’t appear then simple run the “eclipse.exe -clean” option.

4. Now create one project SampleJXB and inside the java source folder create a package like “com.mytest.jxb”

5 Add one XSD with below contents.

<?xml version=”1.0″ encoding=”utf-16″?>

<xsd:schema attributeFormDefault=”unqualified” elementFormDefault=”qualified” version=”1.0″ xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;

<xsd:element name=”persons” />

<xsd:complexType name=”itemsType”>

<xsd:sequence>

<xsd:element maxOccurs=”unbounded” type=”itemType” />

</xsd:sequence>

</xsd:complexType>

<xsd:complexType name=”itemType”>

<xsd:sequence>

<xsd:element name=”firstname” />

<xsd:element name=”lastname” />

<xsd:element name=”email” />

</xsd:sequence>

</xsd:complexType>

</xsd:schema>

6 Now right click on the XSD file and choose JAXB 2.0 -> Run XJC

7 You will be prompted for package name and output directory in the wizard. Simple add the package name given in step 4 and follow the rest of steps.

8 Now navigate to the java package, You will notice 3 classes got generated after running the JAXB command

1. ItemsType.java

2. ItemType.java

3. ObjectFactory.java

9 Now write one Java class to interact with JAXB

import java.io.FileOutputStream;

import java.io.InputStream;

import java.util.List;

import javax.xml.bind.JAXBContext;

import javax.xml.bind.JAXBElement;

import javax.xml.bind.JAXBException;

import javax.xml.bind.Marshaller;

import javax.xml.bind.Unmarshaller;

public class PersonListManager {

private JAXBContext jaxbContext = null;

private Unmarshaller unmarshaller = null;

private ItemsType items = null;

public PersonListManager() {

try {

jaxbContext = JAXBContext.newInstance(“com.mytest.jxb”); //MAKE SURE THE SAME PACAKGE NAME GIVEN IN STEP 4

unmarshaller = jaxbContext.createUnmarshaller();

} catch (JAXBException e) {

}

}

public List loadXML(InputStream istrm) {

try {

Object obj = unmarshaller.unmarshal(istrm);

if(items == null) {

items = (ItemsType)(((JAXBElement)obj).getValue());

return(items.getItem());

}

} catch (JAXBException e) {

e.printStackTrace();

}

return null;

}

/**

* This method will write back to the XML

* @param xmlName

* @throws Exception

*/

public void writeDataInXML(String xmlName) throws Exception{

/* Make sure ItemsType should have @XmlRootElement(name=”items”)if missing add */

ObjectFactory factory= new ObjectFactory();

ItemsType persons = factory.createItemsType();

ItemType item = factory.createItemType();

item.setFirstname(“xyz”);

item.setLastname(“jkl”);

item.setEmail(“anyemail@aa123.com”);

persons.getItem().add(book1);

Marshaller marshaller =jaxbContext.createMarshaller();

marshaller.marshal(library, new FileOutputStream(xmlName)) ;

}

}

10. Now write one more Java class to test the JAXB.

public class TestJAXB {

public static void main(String[] args) {

PersonListManager xmgr = new PersonListManager();

File file = new File(“NewXMLSchema.xml”);

List lst = new ArrayList();

try {

FileInputStream fis = new FileInputStream(file);

lst = xmgr.loadXML(fis);

Iterator<ItemType> lst = rtList.iterator();

while(lst.hasNext()){

ItemType item = lst.next();

System.out.println(“First Name = ” + item.getFirstname().trim() +

“\t\tLast Name = ” + item.getLastname().trim() +

“\t\tEmail = ” + item.getEmail().trim());

}

//xmgr.writeDataInXML(“NewXMLSchema.xml”);

} catch (FileNotFoundException e) {

e.printStackTrace();

}catch(Exception e){

e.printStackTrace();

}

}

}


Thanks
R Vashi

Advertisements