JAXB – Java API for XML Binding

XML Binding

  • XML binding maps XML to objects
  • It generates Classes to represent XML elements. Classes follow JavaBean property access conventions.
  • Supports three principal operations. Marshalling – it marshalls a tree of objects into XML document. Unmarshalling – it unmarshalls an XMl document into a tree of objects. It also validates XML against the schema used to generate classes of objects. Validation of object trees against the schema used to generate classes.

XML Binding Relationships

Why use XML Bindings

  • We do not need to write much code while we have to if we use SAX or DOM
  • We do not need to learn SAX or DOM parser
  • It is less error prone because we do not have to manually implement them and all features of schema are utilized
  • It allows us to customize the XML structure

JAXB Use Cases

  • It is used to create, read or modify XML using Java but without using SAX or DOM parser
  • Using rules defined in XML schema it can validate user input

Now I will show you step by step how we can use JAXB to marshall and unmarshall XMl document easily.

Prerequisites

Eclipse 3.x, JDK 1.6, Maven 2.x, XSD

Step 1. Create a maven project in Eclipse with the below information

Group Id: in.webtuts
Artifact Id: jaxb

Step 2. Modify the pom.xml file to use jar libraries and to generate JAXB classes

Step 3. Put XSD file under src/main/resources/xsd folder. You can use the below sample XSD

Step 4. Now open command prompt and navigate to the project location <project workspace>\jaxb. Execute the below command to build the project

If build is successful, you will get BUILD SUCCESSFUL message and you will see the below classes generated in the folder src/main/java under package – in.webtuts.jaxb.

Catalog.java

ObjectFactory.java

Step 5. Next is we need an XML document which validates against the above XSD. Below is the sample file. Put this XML file under src/main/resources/xml.

Step 6. Now we will create one test class which will marshall or unmarshall the above samle XMl file.

Step 7. Run the above test class and you will get output in the console.

That’s all. Thank you for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.