You are on page 1of 8

JAXB

JAXB is Java Architecture for XML Binding



What Is XML Binding?

Maps XML to in-memory objects according to a schema
Generates classes to represent XML elements
so developers dont have to write them
the binding compiler does this
Supports two primary operations
Marshalling-a tree of objects into an XML document
Unmarshalling-an XML document into a tree of objects

XML Binding Relationships












Why Use XML Binding?

Its easier because we dont have to write as much code

Dont have to learn SAX and/or DOM

It s less error-prone as all the features of the schema are utilized

It can allow customization of the XML structure


JAXB

JAXB defines the behavior of a standard set of tools and interfaces that
automatically generate java class files from XML schema

An XML Binding implementation.Developed through the Java Community Process (JCP)
JAXB is a framework or architecture, not an implementation

Main Functions

Create/Read/Modify XML using Java
but without using SAX or DOM

Validate user input
using rules described in XML Schemas

Use XML-based configuration files
access their values
write tools that create and modify these files

Different from SAX and DOM

SAX and DOM are generic XML parsers
-They will parse any well-structured XML

JAXB creates a parser that is specific to your DTD
-A JAXB parser will parse only valid XML (as defined by your DTD)

DOM and JAXB both produce a tree in memory
-DOM produces a generic tree; everything is a Node
-JAXB produces a tree of Objects with names and attributes as described by your DTD

JAXB is a higher level construct than DOM or SAX
-JAXB represents XML documents as Java classes with properties that are specific to the
particular XML document
E.g. book.xml becomes Book.java with getTitle, setTitle, etc.
JAXB thus requires almost no knowledge of XML to be able to programmatically process XML
documents


Advantages

JAXB requires a DTD-Using JAXB ensures the validity of your XML

A JAXB parser is actually faster than a generic SAX parser

A tree created by JAXB is smaller than a DOM tree

Its much easier to use a JAXB tree for application-specific code

You can modify the tree and save it as XML



JAXB Simple Architecture











Developers write application code and business logic that uses java classes and interfaces
representing XML constructs.
These classes are generated from XML schema using JAXB-provided tools.
When the code must unmarshall XML supplied by some external entity, such as a Web Service,
the JAXB API is invoked to unmarshall the XML, and the data represented there in is populated
in its corresponding Java classes.
Marshalling Convert a Java object into a XML file.
Unmarshalling Convert XML content into a Java Object.

JAXB takes as input two files: your DTD and a binding schema (which you also write)

A binding schema is an XML document written in a binding language defined by
JAXB (with extension .xjs)

The binding schema contains instructions on how to bind a schema to classes.

A minimum binding schema is:
<xml-java-binding-schema>
<element name = "book" type = "class" root = "true" />
</xml-java-binding-schema>


A binding schema is used to customize the JAXB output

Your binding schema can be very simple or quite complex

JAXB produces as output Java source code which you compile and add to your program


JAXB Architectural Overview








A JAXB implementation consists of the following architectural components:
Schema compiler: Binds a source schema to a set of schema-derived program elements. The
binding is described by an XML-based binding language.
Schema generator: Maps a set of existing program elements to a derived schema. The
mapping is described by program annotations.
Binding runtime framework: Provides unmarshalling (reading) and marshalling (writing)
operations for accessing, manipulating, and validating XML content using either schema-
derived or existing program elements.
The JAXB Binding Process




Steps in the JAXB Data Binding process
The general steps in the JAXB data binding process are:
1. Generate classes: An XML schema is used as input to the JAXB binding compiler to
generate JAXB classes based on that schema.
2. Compile classes: All of the generated classes, source files, and application code must be
compiled.
3. Unmarshal: XML documents written according to the constraints in the source schema
are unmarshalled by the JAXB binding framework. Note that JAXB also supports
unmarshalling XML data from sources other than files/documents, such as DOM nodes,
string buffers, SAX Sources, and so forth.
4. Generate content tree: The unmarshalling process generates a content tree of data
objects instantiated from the generated JAXB classes; this content tree represents the
structure and content of the source XML documents.
5. Validate (optional): The unmarshalling process optionally involves validation of the
source XML documents before generating the content tree. Note that if you modify the
content tree in Step 6, below, you can also use the JAXB Validate operation to validate
the changes before marshalling the content back to an XML document.
6. Process content: The client application can modify the XML data represented by the
Java content tree by means of interfaces generated by the binding compiler.
7. Marshal: The processed content tree is marshalled out to one or more XML output
documents. The content may be validated before marshalling.
JAXB provides APIs:
1. javax.xml.bind: contains classes and interfaces for performing operations such as
unmarshalling, marshalling, and validation (marshalling and validation will be covered
later).
2. javax.xml.bind.util, contains a number of utility classes.
3. javax.xml.bind.helper, is designed for JAXB implementation providers.
Binding :
Binding a schema means generating a set of Java classes that represents the schema. All JAXB
implementations provide a tool called a binding compiler to bind a schema .
Eg :- xjc -p hello hello.xsd

Example
JAXB Annotation
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {
String name;
int age;
int id;
public String getName() {
return name;
}

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

publicintgetAge() {
return age;
}

@XmlElement
public void setAge(int age) {
this.age = age;
}

publicintgetId() {
return id;
}

@XmlAttribute
public void setId(int id) {
this.id = id;
}

Convert Object to XML

importjava.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Customer customer = new Customer();
customer.setId(100);
customer.setName("mkyong");
customer.setAge(29);
try {

File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(customer, file);
jaxbMarshaller.marshal(customer, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}

}
}

Output

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<customer id="100">
<age>29</age>
<name>mkyong</name>
</customer>

Convert XML to Object

packagecom.mkyong.core;
importjava.io.File;
importjavax.xml.bind.JAXBContext;
importjavax.xml.bind.JAXBException;
importjavax.xml.bind.Unmarshaller;
public class JAXBExample {
public static void main(String[] args) {
try {

File file = new File("C:\\file.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Customer customer = (Customer) jaxbUnmarshaller.unmarshal(file);
System.out.println(customer);
} catch (JAXBException e) {
e.printStackTrace();
}

}
}

Output

Customer [name=mkyong, age=29, id=100]

You might also like