Monday, October 4, 2010

Simple JAXB Sample

JAXB

Java Architecture for XML Binding (JAXB) helps to read/write XML Document using simple JAVA APIs. Based on the structure of the XSD, JAVA classes and APIs are generated.

JAXB implementation from eclipse can be downloaded from Nightly Build. MoXy(JAXB) has the necessary tools, and runtime jars. To create java classes jaxb-compiler command get used

jaxb-compiler.cmd /tmp/fruits.xsd -d /eclipse/work/TestProject

Now, JAVA files will be created in /eclipse/work/TestProject location under the package jaxbexample.model. Since this package name mentioned in XSD.

fruits.xsd

<?xml version="1.0" encoding="utf-8"?>
<schema targetNamespace="http://mycompany.org/jaxbsample"
 xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
 xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="1.0">
 <annotation>
  <appinfo>
   <jaxb:schemaBindings>
    <jaxb:package name="jaxbexample.model" />
   </jaxb:schemaBindings>
  </appinfo>
 </annotation>


 <element name="Fruits">
  <complexType>
   <sequence>
    <element name="Fruit" maxOccurs="unbounded">
     <complexType>
      <attribute name="name" type="string" />
      <attribute name="qty" type="int" />
      <attribute name="listValue" type="string">
      </attribute>
     </complexType>
    </element>
   </sequence>
  </complexType>
 </element> 
</schema>

UnMarshalling

Load the XML content and convert to JAVA object in runtime.


public static Object unmarshallObject(InputStream is) throws Exception {
  String packageName = "jaxbexample.model";
  JAXBContext context = JAXBContext.newInstance(packageName);
  Unmarshaller unmarshaller = context.createUnmarshaller();
  Object jaxbObject = unmarshaller.unmarshal(is);
  return jaxbObject;

 }

Marshalling

Convert/persist JAVA object into XML Document content.


public static void marshallObject(Object o, String filename) throws Exception {
  String packageName = "jaxbexample.model";
  File f = new File(fileName);
  
  JAXBContext context = JAXBContext.newInstance(packageName);
  Marshaller marshaller = context.createMarshaller();
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

  OutputStream fos = new FileOutputStream(f);
  marshaller.marshal(o, fos);

  try {
   fos.close();
  } finally {
   // do nothing
  }
 }

fruits.xml

Create fruits.xml file in jaxbexamples package as below

<?xml version="1.0" encoding="UTF-8"?>
<Fruits xmlns="http://mycompany.org/jaxbsample" xmlns:ns0="http://mycompany.org/jaxbsample">
   <Fruit name="Apple" qty="10" listValue="Apple,Orange,Banana"/>
   <Fruit name="Orange" qty="5" listValue="Apple,Orange,Banana"/>
   <Fruit name="Banana" qty="20" listValue="Apple,Orange,Banana"/>
</Fruits>

JAXBSample.java


package jaxbexample;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import jaxbexample.model.Fruits;
import jaxbexample.model.Fruits.Fruit;

public class JAXBSample {

 public static void main(String[] args) throws Exception {

  String filename = "./jaxbexample/fruits.xml";
  InputStream is = new FileInputStream(filename);

  Fruits fruits = (Fruits) unmarshallObject(is);

  for (Fruit fruit : fruits.getFruit()) {
   System.out.println("Name : " + fruit.getName() + " Qty:"
     + fruit.getQty());

   fruit.setQty(fruit.getQty() + 1);
  }
  marshallObject(fruits, filename);
 }

 public static Object unmarshallObject(InputStream is) throws Exception {
  String packageName = "jaxbexample.model";
  JAXBContext context = JAXBContext.newInstance(packageName);
  Unmarshaller unmarshaller = context.createUnmarshaller();
  Object jaxbObject = unmarshaller.unmarshal(is);
  return jaxbObject;

 }

 public static void marshallObject(Object o, String filename)
   throws Exception {
  String packageName = "jaxbexample.model";
  File f = new File(filename);

  JAXBContext context = JAXBContext.newInstance(packageName);
  Marshaller marshaller = context.createMarshaller();
  marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

  OutputStream fos = new FileOutputStream(f);
  marshaller.marshal(o, fos);

  try {
   fos.close();
  } finally {
   // do nothing
  }
 }
}

Output

After running first time the above given JAXBSample program, the @qty will be increased by 1.

Name : Apple Qty:11
Name : Orange Qty:6
Name : Banana Qty:21

Some useful links JAXB @ Oracle | jaxb.dev.java.net

No comments:

Post a Comment

Recent Posts

Unix Commands | List all My Posts

Texts

This blog intended to share the knowledge and contribute to JAVA Community such a way that by providing samples and pointing right documents/webpages. We try to give our knowledege level best and no guarantee can be claimed on truth. Copyright and Terms of Policy refer blogspot.com