JAXB Create XML File And Get Data From XML

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

Ads

Tutorials   
JAXB Create XML File And Get Data From XML XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials The Simple API for XML (SAX) APIs Part I XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials XML Tutorial Ignoring Comments While Parsing an XML File Accessing XML file from Java Preventing Expansion of Entity References Getting next Tag in the XML File Replacing a Node with a New One Reading XML Data from a Stream Reading an XML document using JDOM Query XML with an XPath expression Normalize All of the Text in a Document Modifying Text by Replacement Insert a Processing Instruction and a Comment Node Getting text values from a NodeList Finding an ID Value and Print the Element Text Edit Text by Insertion and Replacement Duplicating a Subtree Deleting Two Attributes Delete the First Child of the Root Node Creating XML Tree Creating a DocumentFragment Subtree and Appending it to the Document Creates element node, attribute node, comment node, processing instruction and a CDATA section Creates a New DOM Parse Tree Replacing a Text Node with a New CDATA Section Node Create an Empty DOM Document Adding an Attribute in DOM Document Transforming XML with XSLT Transforming an XML File with XSL Transforming XML with SAXFilters Storing properties in XML file Testing EntityReferences in Xml Splitting One Text Node into Three Reading XML from a File Modifying Text by Cutting and Pasting Locating a Node by Using Siblings Locate a Node and Change Its Content Loading properties from a XML file Listing nodes used in a document Inserting a New Entry in a List Creating an InlineStreamFilter Ignoring Comments While Parsing an XML File Handling Errors While Parsing an XML File Emitting DOCTYPE Declaration while writing XML File Converting CDATA Nodes into Text Nodes Java DOM Tutorial Creating Blank DOM Document
Ads

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;
	}
 
	[email protected]
	@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

Advertisements

Ads
Share on Google+Share on Google+

JAXB Create XML File And Get Data From XML

Posted on: June 8, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

 

Discuss: JAXB Create XML File And Get Data From XML  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0

Ads

 

Ads