JAXB: Example of Nested List of XML Element

Oracle Java
This example demonstrate nested object meaning that , one container class which hold reference of another class. Let say , container class is Employee which hold reference of Address or list of Address , then how you bind in JAXB 2.0.

1. Sample XML with nested element

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookstore>
    <bookList>
        <book id="123" reviewer="ranjeet kumar jha">
            <author>Ranjeet</author>
            <bookName>Real-time Analytics with Storm and Cassandra</bookName>
        </book>
        <book id="124" reviewer="ranjeet Jha">
            <author>Ranjeet</author>
            <bookName>Apache Cassandra Essential</bookName>
        </book>
    </bookList>
    <location>South Ex, Delhi</location>
    <name>Book Mark</name>
</bookstore>

2. Java POJO Container class

In this example BookStore.java is the container class which contains list of Book.java reference. Here, list of Java Object , it means in xml , there will be multiple elements under element.

package com.mysoftkey.jaxb;
 
import java.util.ArrayList;
 
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
 
/**
 * This statement means that class "Bookstore.java" is the root-element of our example
 * //@XmlRootElement(namespace = "com.mysofkey.jaxb.day1")
 * 
 * @author Ranjeet Jha
 *
 */
@XmlRootElement
public class Bookstore {
 
  // XmLElementWrapper generates a wrapper element around XML representation
  @XmlElementWrapper(name = "bookList") 
  // XmlElement sets the name of the entities
  @XmlElement(name = "book")
  private ArrayList<Book> bookList;
 
  private String name;
  private String location;
 
  public void setBookList(ArrayList<Book> bookList) {
	this.bookList = bookList;
  }
 
  public ArrayList<Book> getBooksList() {
	return bookList;
  }
 
  public String getName() {
 	return name;
  }
 
  public void setName(String name) {
 	this.name = name;
  }
 
  public String getLocation() {
	return location;
  }
 
  public void setLocation(String location) {
 	this.location = location;
  }
 
  /**
   * This method is used to add book object into list.
   * 
   * @param book
   */
  public void addBook(Book book) {
  	try {
  	  if (bookList == null) {
		bookList = new ArrayList<Book>();
	  }
	 bookList.add(book);
 
	} catch (Exception e) {
		}
  }
}

3. Java POJO child class

This is child class which added inside the BookStore.java, here you can say , BookStore.java hold references of Book as composition.

File: Book.java
The reference list of Book.java object contains inside BookStore.java class

package com.mysoftkey.jaxb;
 
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
 
@XmlRootElement(name = "book")
// arrange property/element order of xml element, this is Optional
@XmlType(propOrder = { "author", "name" })
public class Book {
 
  private String name;
  private String author;
  private String reviewer;
  private String id;
 
  // If you like the variable name, e.g. "name", you can easily change this
  // name for your XML-Output:
  @XmlElement(name = "bookName")
  public String getName() {
 	return name;
  }
 
  public String getAuthor() {
	return author;
  }
 
  public void setName(String name) {
	this.name = name;
  }
 
  public void setAuthor(String author) {
	this.author = author;
  }
 
  @XmlAttribute
  public String getReviewer() {
	return reviewer;
   }
 
  @XmlAttribute
  public String getId() {
	return id;
  }
 
   public void setReviewer(String reviewer) {
	this.reviewer = reviewer;
  }
 
  public void setId(String id) {
	this.id = id;
  }
 
}

4. Main client to run Application

File: BookMainApp.java
– a java main client for the application to show demo.

package com.mysoftkey.jaxb;
 
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
 
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
 
/**
 * This example shows , how to map nested java object in jaxb 2.0
 * 
 * @author Ranjeet.Jha
 *
 */
public class BookMainApp {
 
  // create a doc folder if not available in side the project
  private static final String BOOKSTORE_XML = "./docs/bookstore.xml";
 
  public static void main(String[] args) throws JAXBException, IOException {
 
	// create book object and populate some values
	Book book1 = new Book();
	book1.setId("123");
	book1.setName("Real-time Analytics with Storm and Cassandra");
	book1.setAuthor("Ranjeet");
	book1.setReviewer("ranjeet kumar jha");
	book1.setId("123");
 
	// create book object and populate some values
	Book book2 = new Book();
	book2.setId("124");
	book2.setName("Apache Cassandra Essential");
	book2.setAuthor("Ranjeet");
	book2.setReviewer("ranjeet Jha");
 
	// create bookstore, assigning book
	Bookstore bookstore = new Bookstore();
	bookstore.setName("Book Mark");
	bookstore.setLocation("South Ex, Delhi");
 
	// add book1 and book2 into bookStore object
	bookstore.addBook(book1);
	bookstore.addBook(book2);
 
	// create JAXB context and instantiate marshaller
	// here bookStore class is container , which contains Book
	JAXBContext context = JAXBContext.newInstance(Bookstore.class);
	Marshaller m = context.createMarshaller();
	m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
 
	// Write to System.out
	m.marshal(bookstore, System.out);
 
	// Write to File
	m.marshal(bookstore, new File(BOOKSTORE_XML));
 
	// read out xml file, and populate values in java object
	// here xml created before are going to read
	System.out.println();
	System.out.println("Output from XML File: ");
	Unmarshaller um = context.createUnmarshaller();
	Bookstore bookstore2 = (Bookstore) um.unmarshal(new FileReader(BOOKSTORE_XML));
	ArrayList<Book> list = bookstore2.getBooksList();
	for (Book book : list) {
		System.out.println("id: " + book.getId() + " , reviewer " + book.getReviewer());
		System.out.print(" , Book name: " + book.getName() + " , author: " + book.getAuthor());
		System.out.print(" location: " + bookstore2.getLocation());
	}
 
  }
 
}

Mashalling Output: java Object to XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<bookstore>
    <bookList>
        <book id="123" reviewer="ranjeet kumar jha">
            <author>Ranjeet</author>
            <bookName>Real-time Analytics with Storm and Cassandra</bookName>
        </book>
        <book id="124" reviewer="ranjeet Jha">
            <author>Ranjeet</author>
            <bookName>Apache Cassandra Essential</bookName>
        </book>
    </bookList>
    <location>South Ex, Delhi</location>
    <name>Book Mark</name>
</bookstore>

Output from XML File:

id: 123 , reviewer ranjeet kumar jha
 , Book name: Real-time Analytics with Storm and Cassandra , author: Ranjeet location: South Ex, Delhiid: 124 , reviewer ranjeet Jha
 , Book name: Apache Cassandra Essential , author: Ranjeet location: South Ex, Delhi

Your comments are welcome to improve this post. Happy Learning 🙂

One thought on “JAXB: Example of Nested List of XML Element

Leave a Reply

Your email address will not be published. Required fields are marked *