JAXB Example of Nested List of XML Element

Connect with

JAXB Example of Nested List of XML ElementLearn JAXB Example of Nested List of XML Element. Nested object, one container class holds a reference to another class. Let say, container class is Employee which holds the reference of Address or list of Address, then how you bind in JAXB 2.0.

1. JAXB exampoe of nested list of XMl element

JAXB example with simple first level chile is easy but when it comes to nested List of object binding then its tricky so learn trick and techniques to bine nested object. You will learn step-by-step process of binding nested list in parent for example in next section you can find nested example xml file.

2. Sample XML with nested element



    
        
            Ranjeet
            Real-time Analytics with Storm and Cassandra
        
        
            Ranjeet
            Apache Cassandra Essential
        
    
    South Ex, Delhi
    Book Mark

3. 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 bookList;

  private String name;
  private String location;

  public void setBookList(ArrayList bookList) {
	this.bookList = bookList;
  }

  public ArrayList 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();
	  }
	 bookList.add(book);

	} catch (Exception e) {
		}
  }
}

4. Java POJO child class

This is a child class added inside the BookStore.java, here you can say, BookStore.java hold references to 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;
  }

}

5. 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 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());
	}

  }

}

5.1 Mashalling Output: java Object to XML



    
        
            Ranjeet
            Real-time Analytics with Storm and Cassandra
        
        
            Ranjeet
            Apache Cassandra Essential
        
    
    South Ex, Delhi
    Book Mark

5.2 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

6. Reference

oracle.com
I hope you enjoyed this post about JAXB example of nested list of xml element, visit Core Java tutorial for more blog post.

Your comment is welcome to improve this post. Happy Learning! 🙂


Connect with

1 thought on “JAXB Example of Nested List of XML Element”

Leave a Comment

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