Home » Core Java » xml » bind » JAXBContext » JAXB Hello World example

About Nikos Maravitsas

Nikos Maravitsas
Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.

JAXB Hello World example

With this example we shall show you how to work with the JAXB framework in Java. JAXB stands for Java Architecture for XML Binding. You can use JAXB to convert an object to XML format and write it to an XML File as well as read an XML File and construct a Java object out of it. These to operations are described in JAXB as:

Marshalling, which converts a Java object into XML format and writes it to an XML File (or generally an output stream).

Unmarshalling, which converts an XML file into a Java object.
 
 

1. JAXB library

As of JDK 1.6, JAXB libraries are included in the JDK. If you are using an older JDK you can download it form the JAXB official project site.

2. JAXB syntax for XML Formatting

JAXB uses annotations to provide meta information that dictates the exact structure of XML elements that will be derived from the class. The annotations are quite straightforward. Of course in the official site you will find all the information you need about JAXB annotations.

Here is the class that we are going to use for the demo:

Student.java:

package com.javacodegeeks.java.core;

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

@XmlRootElement
public class Student {

	//default serialVersion id
    private int id;
	private String firstName;
	private String lastName;
	private int age;

	public Student(){

	}

	public Student(String fname, String lname, int age, int id){
		this.firstName = fname;
		this.lastName  = lname;
		this.age        = age;
		this.id         = id;
	}

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

	public String getFirstName() {
		return this.firstName;
	}

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

	public String getLastName() {
		return this.lastName;
	}

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

	public int getAge() {
		return this.age;
	}

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

	public int getId(){
		return this.id;
	}

	@Override
	public String toString() {
		return new StringBuffer(" First Name : ").append(this.firstName)
				.append(" Last Name : ").append(this.lastName).append(" Age : ").append(this.age).append(" ID : ").append(this.id).toString();
	}

}

3. Marshalling

Remember that Marshalling is the operation that JAXB uses in order to convert an object to XML format and write it to a File.

JXBExampleJava.java

package com.javacodegeeks.java.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JXBExampleJava {

	private static final String xmlFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\Student.xml";

	public static void main(String[] args) {

		Student student = new Student("James", "Jonathan", 25, 100);

		try {

			File xmlfile = new File(xmlFilePath);
			JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
			Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

			// print the output with nice alignment
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			jaxbMarshaller.marshal(student, xmlfile);

			// you can use this to print the result in 
			// standard output for debugging purposes
			// jaxbMarshaller.marshal(student, System.out);

			System.out.println("File was created succesfully");

		} catch (JAXBException e) {
			e.printStackTrace();
		}

	}
}

Student.xml:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<student id="0">
    <age>25</age>
    <firstName>James</firstName>
    <lastName>Jonathan</lastName>
</student>

4. Unmarshalling

Now we are going to do the opposite operation. That is, read an XML File and convert it into a Java Object.

JXBExampleJava.java

package com.javacodegeeks.java.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class JXBExampleJava {

	private static final String xmlFilePath = "C:\\Users\\nikos7\\Desktop\\filesForExamples\\Student.xml";

	public static void main(String[] args) {

		try {

			File xmlFile = new File(xmlFilePath);
			JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);

			Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
			Student student = (Student) jaxbUnmarshaller.unmarshal(xmlFile);
			System.out.println(student);

		} catch (JAXBException e) {
			e.printStackTrace();
		}

	}
}

Output:

  First Name : Jacl Last Name : Freeman Age : 32 ID : 100

 
This was an example on how to work with JAXB in Java.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of