Using JAXB to dealing with your XML


Here i’m going to write down about how to deal with XML by using Java, especially with JAXB as you can see from the subject title.

Why JAXB ?

Of course, there are many ways to handle XML in Java. You could use JAXP API (Java API for XML Processing) which comprises DOMParser and SAXParser (old fashion style and complicated in my opinion ^_^), or XMLBeans which convert and transform your XML file to POJO class or vice versa. I thought the last one (i.e. XMLBeans) is much better compared to JAXP (this is my opinion, maybe you have different opinion). But…, nowadays, i think i would like to choose JAXB rather than XMLBeans. Why ? because (in my private opinion again ^_^), configure JAXB is much simpler than XMLBeans. Because its already become standard of Java EE. Starting from Java 6, its already bundled inside the JDK. So, you don’t need to include external libraries/APIs to use this API. That’s the reason why i choose JAXB instead of XMLBeans.
However, in some IDE (e.g. Oracle Weblogic Workshop), you can see there, that the IDE has already bundled XMLBeans as its standard API to dealing with XML. That’s why, i’m still using XMLBeans for some of my projects that using Oracle Weblogic Workshop as the IDE. However, i’m not talking about XMLBeans here. I will talk about JAXB here. Yes, sure you could find anywhere from the internet (just need to ask uncle google ^_^) about this JAXB. But, I will show you here by example (a simple example), about how easily configure and play with JAXB in order to handling your XML stuffs.

JAXB Overview

First of all for you guys those haven’t already known yet about JAXB. i will tell you here shortly, JAXB stands for Java Architecture for XML Bindings. JAXB is a component part of JAX set API’s. And based on what i have read, studied, and based on my own experience. I can say that as Java Developer, you need and must know about this API. Especially if you’re working with SOA (Service Oriented Architecture) or Middleware stuffs (e.g. Enterprise Application Integration/EAI), you will find there that this JAXB is powerful and one of the most important things you need to know and will help you to improve your life (do i sound excessive ? :-D).
OK, that’s a little bit for the overview section. For details, you can go to ‘uncle’ google :-).

what things you can do with JAXB and how to do those things

Initially, JAXB helps you to do all of these following things:

  • Transform your Java class to XML (marshalling)
  • Read and transform your XML into the Java class (unmarshalling)
  • Generate Java class from XML Schema/xsd file
  • Generate XML schema/xsd from Java class

In order to use JAXB, you need to know about the annotations that provided in JAXB.
Actually, there are many annotations in JAXB. Here, I’ll only give you several annotations that often used as follows:

  • @XmlRootElement
  • @XmlElement
  • @XmlType
  • @XmlElementRef
  • @XmlID
  • @XmlElementWrapper

I will show you soon how to use those annotations above.

First example: Transform your Java class to XML

Lets say, i have Customer class here that i want to transform into the XML file. In order to do that, i will write my Customer class such as following (i will start with the simple example here, later in the next series, i gonna make the example become more complex than this one :-)):
Customer.java

package com.wordpress.yauritux.model;

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

@XmlRootElement(namespace = "com.wordpress.yauritux.model")
public class Customer {
   private String id;
   private String firstName;
   private String lastName;

   @XmlID
   @XmlElement(name = "customer_id")
   public String getId() {
      return id;
   }

   public void setId(String id) {
      this.id = id;
   }

   @XmlElement(name = "customer_firstName")
   public String getFirstName() {
      return firstName;
   }

   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }

   @XmlElement(name = "customer_lastName")
   public String getLastName() {
      return lastName;
   }

   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
}

Compile the class as you can see below:

Click to enlarge
Create the tester (main) class that will transform that class to XML as following:
CustomerMarshalTester.java

package com.wordpress.yauritux;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import com.wordpress.yauritux.model.Customer;

public class CustomerMarshalTester {

   public static void main(String... args) {
      Customer customer = new Customer();
      customer.setId("A 3411144");
      customer.setFirstName("Muhammad Yauri Maulana");
      customer.setLastName("Attamimi");

      try {
         File file = new File("./customer.xml");
         JAXBContext context = JAXBContext.newInstance(Customer.class);
         Marshaller marshaller = context.createMarshaller();

         // give output pretty printed
         marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
         
         marshaller.marshal(customer, file);         
      } catch (JAXBException jaxbException) {
         System.err.println("JAXBException : " + jaxbException.getMessage());
      }
   }
}

Compile the class as following (If you compile from the console like i have done here, so don’t forget to specify the Customer.class in the classpath. You won’t need this if you write your code from the IDE such as Eclipse or Netbeans):

And test the marshaller class as you can see below:

OK, i will try to describe all of those stuffs above as following:
The first class (i.e. Customer.java) is our POJO class that will be transforming into XML. You could see there that i was using 3 annotations known as XmlRootElement, XmlElement, and XmlID, taken from javax.xml.bind.annotation package (don’t forget to import all of those classes before you use). Like i have said before, these classes has been bundled into JDK since JDK 6 as JAXB became standard of Java EE.
Lets start one by one about those elements, starting from :

  1. XmlRootElement
    This annotation is required. You need this element to specify the root element tag of the XML file (I shouldn’t need to explain to you about the root element. I assume that you’ve already known about XML structure. You could ask ‘uncle’ google about that, or just go to w3schools if you need to learn that thing).
    Actually, most of the JAXB annotation have some attributes (one or more attributes) although some annotations do not require any attributes to be defined. Including this XmlRootElement. I don’t know exactly what attributes could be used for this annotation (you could check from JAXB documentation API). Usually, i only use 2 attributes for this annotation (depends on the need, because sometimes i don’t use those attributes at all for this annotation).
    Those 2 attributes that you can use are:

    • namespace
      used to specify the namespace in order to avoids name conflict (similiar with package in Java)
    • name
      used to specify the name of the root element. If you ignore this attribute, then class name will be used as the name of the root element.
  2. XmlID
    This annotation is not required. You will use this annotation if you’d like to denote that the field which came with this annotation will be used (treated) as the ID (yeah, something like primary key in the database model).
  3. XmlElement
    This annotation is not required. This annotation is only use if you want to give different name for your element (if you didn’t specify this annotation, then the field’s name will be used as the name of the element).

The second class (i.e. CustomerMarshalTester.java) is a tester class that will perform marshalling (convert the POJO to XML).
OK guys, we should continue this later. I have to work now. Stay tuned :-D.

About these ads

One thought on “Using JAXB to dealing with your XML

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s