JAXB
Introduction:
- JAXB(Java Architecture for XML Binding) provides API to access and process a XML document
- We can read or write XML files using JAXB. Unlike DOM, SAX or StAX parsers to use JAXB the developer need not be aware of XML parsing techniques.
JAXB Implementation:
- JAXB API is a set of interfaces for which we have various implementations. As part of Metro there is a project for JAXB providing reference implementation. JSR 222 is developed by JCP for JAXB. Latest version of JAXB as of now is JAXB 2.2.
- In this article we use Metro’s JAXB reference implementation. To run the sample code associated, you should download jaxb implementation and the jar files to the classpath.
- There are two operations you can perform using JAXB
1.
Marshalling :Converting a java object to XML
2.
UnMarshalling :Converting a
XML to java object
For Marshaling:
@XmlRootElement:
This annotation defines root element of XML file.
@XmlType(propOrder = {"list of attributes in order"}):This is used to define order of elements in XML file.This is optional.
@XmlElement:This is used to define element in XML file.It sets name of entity.
@XmlType(propOrder = {"list of attributes in order"}):This is used to define order of elements in XML file.This is optional.
@XmlElement:This is used to define element in XML file.It sets name of entity.
@XmlElementWrapper(name
= "name to be given to that wrapper"):It generates a wrapper
element around XML representation.E.g.In above example, it will generate <bookList>
around each <book> element
For Unmarshaling:
Example:
Book.java
package trg.jaxb.bookStore;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="book")
@XmlType(propOrder={"name", "author", "publisher", "isbn"})
public class Book {
private String name;
private String author;
private String isbn;
private String publisher;
public Book() {
super();
}
public Book(String name, String author, String isbn, String publisher) {
super();
this.name = name;
this.author = author;
this.isbn = isbn;
this.publisher = publisher;
}
public String getName() {
return name;
}
@XmlElement(name="title")
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
}
BookStore.java
package trg.jaxb.bookStore;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="bookStore", namespace="trg.jaxb.bookStore")
@XmlType(propOrder={"name", "location", "bookList"})
public class BookStore {
private String name;
private String location;
private List<Book> 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;
}
@XmlElement(name="book")
@XmlElementWrapper(name="bookList")
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
}
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlRootElement(name="bookStore", namespace="trg.jaxb.bookStore")
@XmlType(propOrder={"name", "location", "bookList"})
public class BookStore {
private String name;
private String location;
private List<Book> 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;
}
@XmlElement(name="book")
@XmlElementWrapper(name="bookList")
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
}
JAXBMarshalDemo.java
package trg.jaxb.bookStore;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBMarshalDemo {
private static final String BOOKSTORE_XML = "KharadiBookStore.xml";
public static void main(String[] args) {
List<Book> bookList = new ArrayList<Book>(4);
bookList.add(new Book("Stauts 2 In Action", "A. King", "ISBN-0001", "Wrox Pub."));
bookList.add(new Book("Spring 3 In Action", "B. King", "ISBN-0002", "Apprentice Hall"));
bookList.add(new Book("Hibernate 3 In Action", "C. King", "ISBN-0003", "Kalyani Pub."));
bookList.add(new Book("JSF In Action", "D. King", "ISBN-0004", "ABC Pub."));
BookStore bookStore = new BookStore();
bookStore.setName("Kharadi Book Store");
bookStore.setLocation("Kharadi");
bookStore.setBookList(bookList);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(BookStore.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//render the xml tree on console....
marshaller.marshal(bookStore, System.out);
//write the xml tree to a file
marshaller.marshal(bookStore, new File(BOOKSTORE_XML));
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBMarshalDemo {
private static final String BOOKSTORE_XML = "KharadiBookStore.xml";
public static void main(String[] args) {
List<Book> bookList = new ArrayList<Book>(4);
bookList.add(new Book("Stauts 2 In Action", "A. King", "ISBN-0001", "Wrox Pub."));
bookList.add(new Book("Spring 3 In Action", "B. King", "ISBN-0002", "Apprentice Hall"));
bookList.add(new Book("Hibernate 3 In Action", "C. King", "ISBN-0003", "Kalyani Pub."));
bookList.add(new Book("JSF In Action", "D. King", "ISBN-0004", "ABC Pub."));
BookStore bookStore = new BookStore();
bookStore.setName("Kharadi Book Store");
bookStore.setLocation("Kharadi");
bookStore.setBookList(bookList);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(BookStore.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
//render the xml tree on console....
marshaller.marshal(bookStore, System.out);
//write the xml tree to a file
marshaller.marshal(bookStore, new File(BOOKSTORE_XML));
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
JAXBUnmarshalDemo.java
package trg.jaxb.bookStore;
import java.io.File;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class JAXBUnmarshalDemo {
private static final String BOOKSTORE_XML = "BookStore.xml";
public static void main(String[] args) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(BookStore.class);
System.out.println("Books from .xml file...\n\n");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("D:\\Sidharth\\Web Services\\workspace - WS\\SidWsTrg_JAXB_BookStore\\BookStore.xml"));
doc.getDocumentElement().normalize();
System.out.println("Name : " + doc.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).getNodeValue());
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
BookStore bookStore = (BookStore) unmarshaller.unmarshal(new File(BOOKSTORE_XML));
for(Book book : bookStore.getBookList())
System.out.println("Book -> " + book.getName() + " : " + book.getAuthor() + " : " + book.getPublisher() + " : " + book.getIsbn());
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class JAXBUnmarshalDemo {
private static final String BOOKSTORE_XML = "BookStore.xml";
public static void main(String[] args) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(BookStore.class);
System.out.println("Books from .xml file...\n\n");
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File("D:\\Sidharth\\Web Services\\workspace - WS\\SidWsTrg_JAXB_BookStore\\BookStore.xml"));
doc.getDocumentElement().normalize();
System.out.println("Name : " + doc.getChildNodes().item(0).getChildNodes().item(1).getChildNodes().item(0).getNodeValue());
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
BookStore bookStore = (BookStore) unmarshaller.unmarshal(new File(BOOKSTORE_XML));
for(Book book : bookStore.getBookList())
System.out.println("Book -> " + book.getName() + " : " + book.getAuthor() + " : " + book.getPublisher() + " : " + book.getIsbn());
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Download Link : SidWsTrg_JAXB_BookStore
Generating
Java Beans from XML Schema(.xsd files):
- Download JAXB RI(say jaxb-ri-2.2.6 from metro)
- Set CLASSPATH for jaxb-api.jar, jaxb-impl.jar & jaxb-xjc.jar
- Create xsd’s & run the following command:
$xjc [options] <file>.xsd
E.g. ...\workspace
- WS\SidWsTrg_JAXB_XSD_To_Bean\src>xjc -p trg.jaxb
Employee.xsd
Employee.xsd
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://trg.jaxb/employee" elementFormDefault="qualified"
targetNamespace="http://trg.jaxb/employee">
<xsd:element name="EmployeeDetailsRequest">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="tns:empId" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="EmployeeDetailsResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string" />
<xsd:element name="email" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="empId">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:pattern value="[a-z]{2}[0-9]{5}" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:schema>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:tns="http://trg.jaxb/employee" elementFormDefault="qualified"
targetNamespace="http://trg.jaxb/employee">
<xsd:element name="EmployeeDetailsRequest">
<xsd:complexType>
<xsd:sequence>
<xsd:element ref="tns:empId" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="EmployeeDetailsResponse">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="name" type="xsd:string" />
<xsd:element name="email" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:element name="empId">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:pattern value="[a-z]{2}[0-9]{5}" />
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
</xsd:schema>
Run the below mentioned command(N.B. jars must be at classpath):
\workspace
- WS\SidWsTrg_JAXB_XSD_To_Bean\src>xjc -p trg.jaxb
Employee.xsd
Download Link : SidWsTrg_JAXB_XSD_To_Bean


