JAXB Tutorial – Hello world

The Java™ Architecture for XML Binding (JAXB) provides an API and tools that automate the mapping between XML documents and Java objects.  The JAXB framework enables developers to perform the following operations and in this JAXB tutorial we will see all of them :

  1. Unmarshal XML content into a Java representation
  2. Access and update the Java representation
  3. Marshal the Java representation of the XML content into XML content

 

I used JDK 1.7. Since JAXB is bundled in jdk 1.7 so no dependency is needed.

JAXB Tutorial Examples

Convert Java object to xml

Create a java class with the attributes needed in the xml.

package com.tak.jaxb.tutorial;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class  Phone {
 
 private int id;
 
 private String name;
 
 private String description;

  public int getId() {
  return id;
 }

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

  public String getName() {
  return name;
 }

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

  public String getDescription() {
  return description;
 }

  public void setDescription(String description) {
  this.description = description;
 }

}

Now we marshall the java object to xml using JAXB

package com.tak.jaxb.tutorial;

import java.io.File;
import javax.xml.bind.JAXB;

public class JAXBMarshalExample {
 public static void main(String[] args) {

  Phone phone = new Phone();
  phone.setId(1);
  phone.setName("iPhone 6S");
  phone.setDescription("Phone made by apple");

   File file = new File("C:tempphonefile.xml");
  JAXB.marshal(phone, file);

  }
}

Let us have a look at the xml that was generated.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<phone>
    <description>Phone made by apple</description>
    <id>1</id>
    <name>iPhone 6S</name>
</phone>

 

Convert xml back to Java Object 

And now lets convert the generated xml back to java object

package com.tak.jaxb.tutorial;

import java.io.File;
import javax.xml.bind.JAXB;

public class JAXBUnMarshalExample {
 public static void main(String[] args) {

  File file = new File("C:tempphonefile.xml");
  Phone phone = JAXB.unmarshal(file, Phone.class);
  System.out.println("phone unmarshalled:" + phone.getId());

  }
}

 

1 thought on “JAXB Tutorial – Hello world”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.