Bright Java Tutorial

is brought to you by DoITBright LLC

JAXB

JAXB Example For XML Manipulation

Java Architecture for XML Binding or JAXB is a Java API for manipulating or accessing XML documents. Since JDK 1.8 also known as Java 8, JAXB API is included. We do not need any additional library to get started. I would like to discuss more of what JAXB is through a very simple example. Suppose that we wish to generate XML documents that should look like the XML document below...

  <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <customer id="100">
    <age>29</age>
    <contactList id="1">
      <desc>602-222-2222</desc>
      <type>mobile</type>
    </contactList>
    <contactList id="2">
      <desc>rolan@email.com</desc>
      <type>email</type>
    </contactList>
    <contactList id="3">
      <desc>Phoenix, AZ</desc>
      <type>address</type>
    </contactList>
    <name>rliwanag</name>
  </customer>
                            

As you can see above, the root element of the XML document is a 'customer' tag. A 'customer' tag can have multiple 'contactList' tags inside it. In Java Architecture for XML Binding or JAXB, these will be represented by Java objects. Let us take a look how this is done.

  package com.example.xmlout.jaxb;

  import java.util.List;

  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;
    List contactList;

    public String getName() {
      return name;
    }

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

    public int getAge() {
      return age;
    }

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

    public int getId() {
      return id;
    }

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

    public List getContactList() {
      return contactList;
    }

    @XmlElement
    public void setContactList(List contactList) {
      this.contactList = contactList;
    }

  }
                            


Just by pure observation on the code above, we may probably guess that the class name 'Customer' with an annotation '@XmlRootElement' on top of it means, this will be representing the XML root element. The 'Customer' class has name, age, id and contactList as object properties. These properties have annotations on top of it's set method either with '@XmlElement' or '@XmlAttribute'. our class will have compilation errors because we still need to write our At this point, 'Contact' class. Below is the source code for it.

  package com.example.xmlout.jaxb;

  import javax.xml.bind.annotation.XmlAttribute;
  import javax.xml.bind.annotation.XmlElement;

  public class Contact {

    int id;
    String type;
    String desc;

    public int getId() {
      return id;
    }

    @XmlAttribute
    public void setId(int id) {
      this.id = id;
    }
	
    public String getType() {
      return type;
    }

    @XmlElement
    public void setType(String type) {
      this.type = type;
    }

    public String getDesc() {
      return desc;
    }
	
    @XmlElement
    public void setDesc(String desc) {
      this.desc = desc;
    }
  }
                            


After creating the model classes for the XML binding, let us now look at an example on how to put these classes into action. Here we go...

  package com.example.xmlout.jaxb;

  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;

  /**
   * @author Rolan Liwanag
   */
  public class JAXBExampleMulti {
    public static void main(String[] args) {

      Customer customer1 = new Customer();
      customer1.setId(100);
      customer1.setName("somename");
      customer1.setAge(29);
      List contactList1 = new ArrayList();
	      
      Contact contact1a = new Contact();
      contact1a.setId(1);
      contact1a.setDesc("602-111-2222");
      contact1a.setType("mobile");
      contactList1.add(contact1a);
      
      Contact contact2a = new Contact();
      contact2a.setId(2);
      contact2a.setDesc("example@email.com");
      contact2a.setType("email");
      contactList1.add(contact2a);
	      
      Contact contact3a = new Contact();
      contact3a.setId(3);
      //this wont be included in the XML since value is null.
      contact3a.setDesc(null);
      contact3a.setType("address");
      contactList1.add(contact3a);
	      
      customer1.setContactList(contactList1);
      
      Customer customer2 = new Customer();
      customer2.setId(100);
      customer2.setName("rliwanag");
      customer2.setAge(29);
      List contactList2 = new ArrayList();
	      
      Contact contact1b = new Contact();
      contact1b.setId(1);
      contact1b.setDesc("602-222-2222");
      contact1b.setType("mobile");
      contactList2.add(contact1b);
	      
      Contact contact2b = new Contact();
      contact2b.setId(2);
      contact2b.setDesc("rolan@email.com");
      contact2b.setType("email");
      contactList2.add(contact2b);
	      
      Contact contact3b = new Contact();
      contact3b.setId(3);
      contact3b.setDesc("Phoenix, AZ");
      contact3b.setType("address");
      contactList2.add(contact3b);
	      
      customer2.setContactList(contactList2);
	      
      List customerList = new ArrayList();
      customerList.add(customer1);
      customerList.add(customer2);
      try {
        JAXBContext jaxbContext 
          = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller 
          = jaxbContext.createMarshaller();
        // output pretty printed
        jaxbMarshaller.setProperty(
          Marshaller.JAXB_FORMATTED_OUTPUT, true);
        for(int i=0; i<customerList.size(); i++) {
          Customer customer = customerList.get(i);
          File file 
            = new File(
              "C:/workspace/CoreExample/outputFile/xmlFileJaxb_" 
              + i + ".xml");
          jaxbMarshaller.marshal(customer, file);
          jaxbMarshaller.marshal(customer, System.out);
        }
      } catch (JAXBException e) {
        e.printStackTrace();
      }
    }
  }
                            


Summarizing the idea regarding the code shown above, the firswt part is more of initializing several 'Customer' object with either 1 or many 'Contact' object associated to each. The latter part of the code is simply generating the XML file for each 'Customer' object by invoking the 'marshal' method of the 'javax.xml.bind.Marshaller' instance. In this example, we have learned how to use Java objects to generate XML documents using the Java Architecture for XML Binding or JAXB.