JAXB UnMarshal Tutorial With Example
Java Architecture for XML Binding (JAXB) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and, to unmarshal XML back into Java objects.
Let’s quickly dive into an example:
Here is the xml file
<?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML. </description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world. </description> </book> <book id="bk103"> <author>Corets, Eva</author> <title>Maeve Ascendant</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-11-17</publish_date> <description>After the collapse of a nanotechnology society in England, the young survivors lay the foundation for a new society. </description> </book> <book id="bk104"> <author>Corets, Eva</author> <title>Oberon's Legacy</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-03-10</publish_date> <description>In post-apocalypse England, the mysterious agent known only as Oberon helps to create a new life for the inhabitants of London. Sequel to Maeve Ascendant. </description> </book> <book id="bk105"> <author>Corets, Eva</author> <title>The Sundered Grail</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2001-09-10</publish_date> <description>The two daughters of Maeve, half-sisters, battle one another for control of England. Sequel to Oberon's Legacy. </description> </book> <book id="bk106"> <author>Randall, Cynthia</author> <title>Lover Birds</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-09-02</publish_date> <description>When Carla meets Paul at an ornithology conference, tempers fly as feathers get ruffled. </description> </book> <book id="bk107"> <author>Thurman, Paula</author> <title>Splish Splash</title> <genre>Romance</genre> <price>4.95</price> <publish_date>2000-11-02</publish_date> <description>A deep sea diver finds true love twenty thousand leagues beneath the sea. </description> </book> <book id="bk108"> <author>Knorr, Stefan</author> <title>Creepy Crawlies</title> <genre>Horror</genre> <price>4.95</price> <publish_date>2000-12-06</publish_date> <description>An anthology of horror stories about roaches, centipedes, scorpions and other insects. </description> </book> <book id="bk109"> <author>Kress, Peter</author> <title>Paradox Lost</title> <genre>Science Fiction</genre> <price>6.95</price> <publish_date>2000-11-02</publish_date> <description>After an inadvertant trip through a Heisenberg Uncertainty Device, James Salway discovers the problems of being quantum. </description> </book> <book id="bk110"> <author>O'Brien, Tim</author> <title>Microsoft .NET: The Programming Bible</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-09</publish_date> <description>Microsoft's .NET initiative is explored in detail in this deep programmer's reference. </description> </book> <book id="bk111"> <author>O'Brien, Tim</author> <title>MSXML3: A Comprehensive Guide</title> <genre>Computer</genre> <price>36.95</price> <publish_date>2000-12-01</publish_date> <description>The Microsoft MSXML3 parser is covered in detail, with attention to XML DOM interfaces, XSLT processing, SAX and more. </description> </book> <book id="bk112"> <author>Galos, Mike</author> <title>Visual Studio 7: A Comprehensive Guide</title> <genre>Computer</genre> <price>49.95</price> <publish_date>2001-04-16</publish_date> <description>Microsoft Visual Studio 7 is explored in depth, looking at how Visual Basic, Visual C++, C#, and ASP+ are integrated into a comprehensive development environment. </description> </book> </catalog> |
Now we define the appropriate POJO’s for the above xml.
Create a class Catalog who’s structure is given below
import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "catalog") public class Catalog { List<Book> books; @XmlElement(name = "book") public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } } |
Create a class Book who’s structure is given below
package com.mdoffice; import java.util.Date; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "Book") public class Book { private String id; private String author; private String title; private String genre; private double price; private Date publish_date; private String description; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getTitle() { return title; } @XmlAttribute(name = "id") public String getId() { return id; } public void setId(String id) { this.id = id; } public void setTitle(String title) { this.title = title; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public Date getPublish_date() { return publish_date; } public void setPublish_date(Date publish_date) { this.publish_date = publish_date; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Author: ").append(this.getAuthor()) .append("\nDescription: ").append(this.getDescription()) .append("\nGenre: ").append(this.getGenre()).append("\nId: ") .append(this.getId()).append("\nPrice: ") .append(this.getPrice()).append("\nTitle: ") .append(this.getTitle()).append("\nPublishedDate: ") .append(this.getPublish_date()); return sb.toString(); } } |
Now create BookCatalog class.
If you are only interested in the unmarshalling process just look at the BookCatalog constructor.
import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; public class BookCatalog { private List<Book> books; private Catalog catalog; public BookCatalog() { try { File file = new File("books.xml"); JAXBContext jaxbContext = JAXBContext.newInstance(Catalog.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); this.catalog = (Catalog) jaxbUnmarshaller.unmarshal(file); books = this.catalog.getBooks(); } catch (JAXBException e) { e.printStackTrace(); } } public static void main(String[] args) { BookCatalog bookCatalog = new BookCatalog(); System.out.println("--------------findBookByGenre-Horror--------------------"); List<Book> a = bookCatalog.findBookByGenre("Horror"); for (Book t : a) { System.out.println(t); System.out.println("-----------"); } System.out.println("--------------findBookByAuthor--------------------"); List<Book> auth = bookCatalog.findBookByAuthor("Ralls, Kim"); for (Book t : auth) { System.out.println(t); System.out.println("-----------"); } System.out.println("--------------findBookByPublishDate--------------------"); Calendar c1 = Calendar.getInstance(); c1.set(2000, 2, 1); Calendar c2 = Calendar.getInstance(); c2.set(2001, 12, 1); Date startDate = c1.getTime(); Date endDate = c2.getTime(); List<Book> pubDate = bookCatalog.findBookByPublishDate(startDate, endDate); for (Book t : pubDate) { System.out.println(t); System.out.println("-----------"); } System.out.println("--------------Actual Books Published Date--------------------"); for (Book t : bookCatalog.books) { System.out.println(t.getPublish_date()); } System.out.println("--------------sortBookByPublishDate--------------------"); List<Book> b = bookCatalog.sortBookByPublishDate(bookCatalog.books); for (Book c : b) { System.out.println(c.getPublish_date()); } System.out.println("--------------Actual Books Author Unsorted--------------------"); for (Book t : bookCatalog.books) { System.out.println(t.getAuthor()); } System.out.println("-------------sortBooksByAuthor--------------------"); List<Book> b1 = bookCatalog.sortBooksByAuthor(bookCatalog.books); for (Book t1 : b1) { System.out.println(t1.getAuthor()); } System.out.println("--------------UnsortedBookPrice--------------------"); for (Book t : bookCatalog.books) { System.out.println(t.getPrice()); } System.out.println("--------------SortedBookPrice--------------------"); List<Book> b2 = bookCatalog.sortBookByPrice(bookCatalog.books); for (Book t1 : b2) { System.out.println(t1.getPrice()); } } public Catalog getCatalog() { return catalog; } public void setCatalog(Catalog catalog) { this.catalog = catalog; } public List<Book> getBooks() { return books; } public void setBooks(List<Book> books) { this.books = books; } public List<Book> findBookByGenre(String genre) { List<Book> result = new ArrayList<Book>(); for (Book book : books) { if (book.getGenre().equals(genre)) { result.add(book); } } return result; } public List<Book> findBookByAuthor(String author) { List<Book> result = new ArrayList<Book>(); for (Book book : books) { if (book.getAuthor().equals(author)) { result.add(book); } } return result; } public List<Book> findBookByPrice(double startPrice, double endPrice) { List<Book> result = new ArrayList<Book>(); for (Book book : books) { double price = book.getPrice(); if (price >= startPrice && price <= endPrice) { result.add(book); } } return result; } public List<Book> findBookByPublishDate(Date startDate, Date endDate) { List<Book> result = new ArrayList<Book>(); for (Book book : books) { Date d = book.getPublish_date(); if (d.after(startDate) && d.before(endDate)) { result.add(book); } } return result; } public List<Book> sortBooksByAuthor(List<Book> book) { List<Book> b = book; Collections.sort(b, new BookAuthorComparator()); return b; } public List<Book> sortBookByPrice(List<Book> book) { List<Book> b = book; Collections.sort(b, new BookPriceComparator()); return b; } public List<Book> sortBookByPublishDate(List<Book> book) { List<Book> b = book; Collections.sort(b, new BookPublishComparator()); return b; } public class BookPublishComparator implements Comparator<Book> { public int compare(Book a, Book b) { return a.getPublish_date().compareTo(b.getPublish_date()); } } public class BookAuthorComparator implements Comparator<Book> { public int compare(Book a, Book b) { return a.getAuthor().compareTo(b.getAuthor()); } } public class BookPriceComparator implements Comparator<Book> { public int compare(Book a, Book b) { return Double.valueOf(a.getPrice()).compareTo( Double.valueOf(b.getPrice())); } } } |
The following is the unit test cases for the BookCatalog class:
import static org.junit.Assert.fail; import java.util.Calendar; import java.util.Date; import java.util.List; import junit.framework.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.mdoffice.Book; import com.mdoffice.BookCatalog; public class BookCatalogTest { public static BookCatalog b; @BeforeClass public static void runBeforeClass() { b = new BookCatalog(); } @Test public void testFindBookByGenre() { Assert.assertTrue((b.findBookByGenre("Computer")).size() > 0); } @Test public void testFindBookByAuthor() { Assert.assertTrue((b.findBookByAuthor("Ralls, Kim")).size() > 0); } @Test public void testFindBookByPrice() { Assert.assertTrue((b.findBookByPrice(10, 50)).size() > 0); } @Test public void testFindBookByPublishDate() { Calendar c1 = Calendar.getInstance(); c1.set(2000, 2, 1); Calendar c2 = Calendar.getInstance(); c2.set(2013, 12, 1); Date startDate = c1.getTime(); Date endDate = c2.getTime(); Assert.assertTrue((b.findBookByPublishDate(startDate, endDate)).size() > 0); } @Test public void testSortBooksByAuthor() { List<Book> books = b.sortBooksByAuthor(b.getBooks()); String firstBook = books.get(0).getAuthor(); String secondBook = ""; int length = books.size(); for (int i = 1; i < length; i++) { secondBook = books.get(i).getAuthor(); if (firstBook.compareTo(secondBook) > 0) { fail("Sort Books By Author failed"); break; } else { firstBook = secondBook; } } } @Test public void testSortBookByPrice() { List<Book> books = b.sortBookByPrice(b.getBooks()); double firstBook = books.get(0).getPrice(); double secondBook = 0; int length = books.size(); for (int i = 1; i < length; i++) { secondBook = books.get(i).getPrice(); if (Double.valueOf(firstBook).compareTo(Double.valueOf(secondBook)) > 0) { fail("Sort Books By Price failed"); break; } else { firstBook = secondBook; } } } @Test public void testSortBookByPublishDate() { List<Book> books = b.sortBookByPublishDate(b.getBooks()); Date firstBook = books.get(0).getPublish_date(); Date secondBook = null; int length = books.size(); for (int i = 1; i < length; i++) { secondBook = books.get(i).getPublish_date(); if (firstBook.compareTo(secondBook) > 0) { fail("Sort Books By Publish Date failed"); break; } else { firstBook = secondBook; } } } } |
tal
finally some one who explains by example, and writes all the missing peaces, thanks your tutorial with example helped when all others didn’t.