Back to top

vogella training Training Books

JAXB Tutorial

Lars Vogel

Version 1.6

23.11.2012

Revision History
Revision 0.1 26.02.2008 Lars
Vogel
created
Revision 0.2 - 1.6 21.10.2008 - 23.11.2012 Lars Vogel bug fixes and enhancements

JAXB Tutorial

This tutorial give an introduction to Java Architecture for XML Binding (JAXB). This tutorial is based on Java 6.0.


Table of Contents

1. Overview
2. Prerequisitions
3. JAXB 2 - Java Architecture for XML Binding
4. Tutorial: Using JAXB
5. Thank you
6. Questions and Discussion
7. Links and Literature
7.1. Source Code
7.2. Links and Literature
7.3. vogella Resources

1. Overview

Java Architecture for XML Binding (JAXB) is a Java standard that defines how Java objects are converted from and to XML. It uses a standard set of mappings.

JAXB defines an API for reading and writing Java objects to and from XML documents.

As JAXB is defined via a specification, it is possible to use different implementations for this standard. JAXB defines a service provider which allows the selection of the JAXB implementation.

It applies a lot of defaults thus making reading and writing of XML via Java relatively easy.

2. Prerequisitions

The following will demonstrate the JAXB API. For an introduction into using XML with Java please see Java XML tutorial.

3. JAXB 2 - Java Architecture for XML Binding

JAXB uses annotations to indicate the central elements.

Table 1. 

Annotation Description
@XmlRootElement(namespace = "namespace") Define the root element for a XML tree
@XmlType(propOrder = { "field2", "field1",.. }) Allows to define the order in which the fields are written in the XML file
@XmlElement(name = "neuName") Define the XML element which will be used. Only need to be used if the neuNeu is different then the JavaBeans Name


4. Tutorial: Using JAXB

Create a new Java project called "de.vogella.xml.jaxb".

Create the following domain model with the JAXB annotations.

package de.vogella.xml.jaxb.model;

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

@XmlRootElement(name = "book")
// If you want you can define the order in which the fields are written
// Optional
@XmlType(propOrder = { "author", "name", "publisher", "isbn" })
public class Book {

  private String name;
  private String author;
  private String publisher;
  private String isbn;

  // If you like the variable name, e.g. "name", you can easily change this
  // name for your XML-Output:
  @XmlElement(name = "title")
  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getAuthor() {
    return author;
  }

  public void setAuthor(String author) {
    this.author = author;
  }

  public String getPublisher() {
    return publisher;
  }

  public void setPublisher(String publisher) {
    this.publisher = publisher;
  }

  public String getIsbn() {
    return isbn;
  }

  public void setIsbn(String isbn) {
    this.isbn = isbn;
  }

} 

package de.vogella.xml.jaxb.model;

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 = "de.vogella.xml.jaxb.model")
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;
  }
} 

Create the following test program for writing and reading the XML file.

package test;

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;

import de.vogella.xml.jaxb.model.Book;
import de.vogella.xml.jaxb.model.Bookstore;

public class BookMain {

  private static final String BOOKSTORE_XML = "./bookstore-jaxb.xml";

  public static void main(String[] args) throws JAXBException, IOException {

    ArrayList<Book> bookList = new ArrayList<Book>();

    // create books
    Book book1 = new Book();
    book1.setIsbn("978-0060554736");
    book1.setName("The Game");
    book1.setAuthor("Neil Strauss");
    book1.setPublisher("Harpercollins");
    bookList.add(book1);

    Book book2 = new Book();
    book2.setIsbn("978-3832180577");
    book2.setName("Feuchtgebiete");
    book2.setAuthor("Charlotte Roche");
    book2.setPublisher("Dumont Buchverlag");
    bookList.add(book2);

    // create bookstore, assigning book
    Bookstore bookstore = new Bookstore();
    bookstore.setName("Fraport Bookstore");
    bookstore.setLocation("Frankfurt Airport");
    bookstore.setBookList(bookList);

    // create JAXB context and instantiate marshaller
    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));

    // get variables from our xml file, created before
    System.out.println();
    System.out.println("Output from our 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("Book: " + book.getName() + " from "
          + book.getAuthor());
    }
  }
} 

If you run the BookMain a XML file will be created from the input objects. Afterwards the file is read again and the objects are re-created based on the XML file.

5. Thank you

Please help me to support this article:

Flattr this

6. Questions and Discussion

Before posting questions, please see the vogella FAQ. If you have questions or find an error in this article please use the www.vogella.com Google Group. I have created a short list how to create good questions which might also help you.

7. Links and Literature

7.1. Source Code

Source Code of Examples

7.2. Links and Literature

http://www.vogella.com/articles/RSSFeed/article.html Read and write RSS feeds via Java (Stax)

http://java.sun.com/developer/technicalArticles/WebServices/jaxb/ JAXB Overview

http://www.ibm.com/developerworks/library/x-javaxpathapi.html The Java XPath API (by Elliotte Rusty Harold)

7.3. vogella Resources

vogella Training Android and Eclipse Training from the vogella team

Android Tutorial Introduction to Android Programming

GWT Tutorial Program in Java and compile to JavaScript and HTML

Eclipse RCP Tutorial Create native applications in Java

JUnit Tutorial Test your application

Git Tutorial Put everything you have under distributed version control system