Saturday, May 25, 2013

JAXB: Marshalling/Unmarshalling Example

This post shows how you can marshal a JAXB object into XML and unmarshal XML into a JAXB object.

Consider the following JAXB class:

import javax.xml.bind.annotation.*;

public class Book {

  private String author;

  private String title;
To convert an XML string into an object of class Book:
public static Book unmarshal(final String xml) throws JAXBException {
  return (Book) JAXBContext.newInstance(Book.class)
                           .unmarshal(new StringReader(xml));
To convert a Book object into an XML string:
public static String marshal(Book book) throws JAXBException {
  final Marshaller m = JAXBContext.newInstance(Book.class)
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
  final StringWriter w = new StringWriter();
  m.marshal(book, w);
  return w.toString();


  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Java Online Training Java Online Training