Sunday, February 2, 2014
Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations. JAXB provides methods for reading XML documents into Java objects and writing Java objects into XML documents.

JAXB annotations are used for customizing Java program elements to XML mapping. Refer to this link for list of annotations supported.

In this example below we use JAXB to write an XML document from Java objects and to read an XML document into Java objects. 

Some of the annotations we use in this example.
  1. XmlRootElement - Maps a class or an enum type to an XML element.
  2. XmlElement - Maps a JavaBean property to a XML element derived from property name.
  3. XmlAttribute - Maps a JavaBean property to a XML attribute.
First we need to create the necessary Java objects to hold our data. We create a Book object and a Catalog object to hold bunch of books. We use XmlRootElement annotation to the class and XmlAttribute annotation to the id property. Other properties are interpreted by default as XmlElement.

package com.sourcetricks.jaxb;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="book")
public class Book {

 private String id;
 private String title;
 private String author;
 private String genre;
 private String price;
 private String description;
 
 @XmlAttribute(name="id")
 public String getId() {
  return id;
 }
 public String getTitle() {
  return title;
 }
 public String getAuthor() {
  return author;
 }
 public String getGenre() {
  return genre;
 }
 public String getPrice() {
  return price;
 }
 public String getDescription() {
  return description;
 }
 public void setId(String id) {
  this.id = id;
 } 
 public void setTitle(String title) {
  this.title = title;
 }
 public void setAuthor(String author) {
  this.author = author;
 }
 public void setGenre(String genre) {
  this.genre = genre;
 }
 public void setPrice(String price) {
  this.price = price;
 }
 public void setDescription(String description) {
  this.description = description;
 }
}

Next we create a catalog object that holds a list of books.

package com.sourcetricks.jaxb;

import java.util.ArrayList;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="catalog")
public class Catalog {

 @XmlElement(name="book")
 private ArrayList<Book> listOfBooks;
 
 public Catalog() {
  listOfBooks = new ArrayList<Book>();
 }
 
 public void addBook(Book book) {
  listOfBooks.add(book);
 }
 
 public void printBooks() {
  for ( Book b : listOfBooks ) {
   System.out.println(b.getId());
   System.out.println(b.getTitle());
   System.out.println(b.getAuthor());
   System.out.println(b.getGenre());
   System.out.println(b.getPrice());
  }
 }
}
Finally the test program which marshals and unmarshals the XML documents.
package com.sourcetricks.jaxb;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

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

public class JaxbTest {

 private void marshalTest() {
  // Create a catalog
  Catalog catalog = new Catalog();

  // Add some books
  Book book1 = new Book();
  book1.setId("100");
  book1.setTitle("XML Developer's Guide");
  book1.setAuthor("Gambardella, Matthew");
  book1.setGenre("Computer");
  book1.setPrice("44.95");
  book1.setDescription("An in-depth look at creating applications with XML");
  catalog.addBook(book1);

  // Marshal the catalog object into XML
  try {
   JAXBContext context = JAXBContext.newInstance(Catalog.class);
   Marshaller marshaller = context.createMarshaller();
   // Format the output
   marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
   System.out.println("------------- Marshal Test----------------------");
   marshaller.marshal(catalog, System.out);   
  } catch (JAXBException e) {
   e.printStackTrace();
  }
 }
 
 public void unmarshalTest() {
  FileReader reader = null;
  // Read an XML document and unmarshal into Java objects
  try {
   reader = new FileReader("resources/input.xml");  
   JAXBContext context = JAXBContext.newInstance(Catalog.class);
   Unmarshaller unmarshaller = context.createUnmarshaller();
   Catalog c = (Catalog) unmarshaller.unmarshal(reader);
   System.out.println("------------- Unmarshal Test----------------------");
   c.printBooks();
  } 
  catch ( FileNotFoundException e ) {
   e.printStackTrace();
  } 
  catch (JAXBException e) {
   e.printStackTrace();
  } 
  finally {
   if ( reader != null )
    try {
     reader.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
  }
 }

 public static void main(String[] args) {
  JaxbTest j = new JaxbTest();
  j.marshalTest();
  j.unmarshalTest();  
 }
}
Output
------------- Marshal Test----------------------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<catalog>
    <book id="100">
        <author>Gambardella, Matthew</author>
        <description>An in-depth look at creating applications with XML</description>
        <genre>Computer</genre>
        <price>44.95</price>
        <title>XML Developer's Guide</title>
    </book>
</catalog>
------------- Unmarshal Test----------------------
bk101
XML Developer's Guide
Gambardella, Matthew
Computer
44.95

0 comments :

Post a Comment

Contact Form

Name

Email *

Message *

Back to Top