Home Xml JAXB Create XML File And Get Data From XML
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JAXB Create XML File And Get Data From XML

Advertisement
JAXB (Java Architecture for XML Binding) is used for creating XML file from Java object and convert from XML data to Java object.

JAXB Create XML File And Get Data From XML

In this section we will read about how to create XML file and how to convert XML file's data to Java Object using JAXB. Since we are going to do work with the XML files and using JAXB a new technology so we would have to check their dependency. From the JDK version 1.6 there is no need to download the JAXB explicitly because it is bundled with this version. But, prior to JDK 1.6 to work with JAXB one would have to download the "jaxb-api.jar" and "jaxb-impl.jar" jar files explicitly. In this tutorial we are using JDK 1.6 so we don't have to download the JAXB jars explicitly.

Availability of JAXB or the ability to integrate the Java code and JAXB codes has made easy to work with XML files. We can use JAXB annotation to annotate the Java Object and then we can use marshal() method to write the Java Objects into a XML file and unmarshal() method to read XML data as Java Object.

JAXB Version

At the time of writing this tutorial the latest version of JAXB is 2.2.6. If you are required to download the JAXB explicitly then you may go through the following link Download JAXB

Example :

Here we are giving a simple example into which we will first create an XML file using Java Object then we will read that XML data as Java Object again. In this example at first we will create Java Classes to create an XML file using Java Objects at the specified place then we will create another Java classes for reading that XML data as Java Objects. Now, We will first create a Java bean class named Emplyee.java which will contain some data members and their setter-getter methods to set/get their values. We will specify in the Java class which will be the root element and the sub elements using @XmlRootElement and @XmlElement annotations. Besides these annotations you can use several more annotations like @XmlAttribute to specify the attribute of element. Then we will create a class named EmployeeList to set the Employee into a list and get them return from list (This class will help in to add multiple employees and get them back.). Then we will create a Java class named WriteToXmlFile.java for writing the Java object into XML file. In this class we will use the following classes, methods and constant fields of JAXB API :

  • JAXBContext : This class is used to specify the entry point of client.
  • Marshaller : This class is used to enforce the rules on procedure of serializing the Java contents into a tree structure into XML data.
  • createMarhaller() : This method is used to create the Marshaller object that is used to convert the Java content into XML data.
  • setProperty() : This method is used to set the specified property of Marshaller.
  • Marshaller.JAXB_FORMATTED_OUTPUT : This field property specifies the formatting property of marshalled XML data with linefeeds and indentation. The boolean value with this field used in the setProperty() method specifies whether XML data should be formatted using the specified filed property or not.
  • marshal() : This method is used to marshal the content.

Next to retrieve the data back from XML to Java content we will create a Java class named ReadFromXmlFile.java. In this class we will again use the following classes, methods, constant fields of JAXB API :

  • JAXBContext : As we have discussed earlier this class is used to specify the entry point of client.
  • Unmarshaller : This class is used to enforce the rules on procedure of deserializing the XML data into Java contents.
  • createUnmarshaller() : This method is used to create the Unmarshaller object that is used to convert XML data into Java content.
  • unmarshal() : This method is used to unmarshal the XML data of the specified file.

Employee.java

package net.roseindia.xml;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
 
@XmlRootElement(name="employee")
public class Employee {
 
	String name;
	int age;
	int id;
 
	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
	@XmlElement
	public void setId(int id) {
		this.id = id;
	}
 
}

EmployeeList.java

package net.roseindia.xml;

import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="employeelist")
@XmlAccessorType(XmlAccessType.FIELD)
public class EmployeeList {

	List employee;
	
	public List getEmployeeList() {
		return employee;
	}

	public void setEmployeeList(List employee) {
		this.employee = employee;
	}	
}

WriteToXmlFile.java

package net.roseindia.xml;

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;
 
public class WriteToXmlFile {
	public static void main(String[] args) {
 
		Employee employee;
		EmployeeList empList=new EmployeeList();
	    List list=new ArrayList();
	    employee = new Employee();
	    employee.setId(1);
	    employee.setName("Deepak");
	    employee.setAge(29);
	    list.add(employee);
	    employee = new Employee();
	    employee.setId(2);
	    employee.setName("Rose");
	    employee.setAge(30);
	    list.add(employee);
	    empList.setEmployeeList(list);
	  try {
 
		File file = new File("C:\\Documents and Settings\\bharat\\Desktop\\bipul\\CoreJava\\employee.xml");
		JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeList.class);
		Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
 
		// output pretty printed
		jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 
		jaxbMarshaller.marshal(empList, file);		
		jaxbMarshaller.marshal(empList, System.out);
 
	      } catch (JAXBException e) {
		e.printStackTrace();
	      } 
	}
}

When you will compile and execute the WriteToXmlFile.java file then the output will be as follows :

Following output will be shown on your console as well as specified XML file will be created in the specified directory.

Now the following Java file demonstrates how to retrieve the XML data as Java content. Here we will get the data after validating the input value i.e. this class will display only those employee record which employee name is matched to the input name given by the user.

ReadFromXmlFile.java

package net.roseindia.xml;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
 
public class ReadFromXmlFile {
	public static void main(String[] args) {
		String empName="";		
		Iterator itr;
 
	 try {
 
		File file = new File("C:\\Documents and Settings\\bharat\\Desktop\\bipul\\CoreJava\\employee.xml");
		JAXBContext jaxbContext = JAXBContext.newInstance(EmployeeList.class);
 
		Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
		Scanner scan = new Scanner(System.in);
		System.out.println("Enter employee name");
		String name = scan.nextLine();
		EmployeeList emp = (EmployeeList) jaxbUnmarshaller.unmarshal(file);
		List empList = emp.getEmployeeList();
		itr = empList.iterator();
		while(itr.hasNext())
		{
			Employee employee = (Employee) itr.next();			
			empName = employee.getName();
			if(empName.equals(name))
			{
				System.out.println("Emp ID : "+employee.getId());
				System.out.println("Emp Name : "+employee.getName());
				System.out.println("Emp Age : "+employee.getAge());
			}			
		}	
 
	  } catch (JAXBException e) {
		e.printStackTrace();
	  }
 
	}
}

Output

When you will compile and execute the ReadFromXmlFile.java then the output will be as follows :

On successfully execution of the above Java class on console the user will be asked for input the name of employee and when you will give the correct name as available in the XML file, for example, I have given Deepak, then the output will be as follows :

Download Source Code

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 8, 2013

Ask Questions?    Discuss: JAXB Create XML File And Get Data From XML  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com