convert xml into java object using jaxb


Convert xml into java object using jaxb

By the help of Unmarshaller interface of javax.xml.bind package we can convert xml into java object using jaxb, this process is also knows as Unmarshalling in java.

JAXB Unmarshalling Example

To convert XML data into object we have to follow some steps in java, Here we will understand Unmarshalling with simple XML  example.

Converting XML into Object

  1. Create StudentInfo.java  POJO class.
  2. Annotate POJO class with @XmlRootElement
  3. Create student.xml File.
  4. Create StudentParser.java  class with main method.

student.xml

<?xml version="1.0" encoding="UTF-8"?>
<student>
 <roll>101</roll>
 <name>Vikash</name>
 <address>Hyderabad</address>
</student>

StudentInfo.java

Here StudentInfo class with  @XmlRootElement annotation and pass name inside @XmlRootElement annotation like below.

@XmlRootElement(name = "student")

Here name represent root element of student.xml file.

package com.javagf.pojo;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "student")
public class StudentInfo {
 private int roll;
 private String name;
 private String address;

 public int getRoll() {
 return roll;
 }

 public void setRoll(int roll) {
 this.roll = roll;
 }

 public String getName() {
 return name;
 }

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

 public String getAddress() {
 return address;
 }

 public void setAddress(String address) {
 this.address = address;
 }

 @Override
 public String toString() {
 return "StudentInfo [roll=" + roll + ", name=" + name + ", address="
 + address + "]";
 }

}

Here you need to maintain POJO class attribute same as XML element name , if you don’t want to keep POJO class attribute name same as XML element name then you have to use @XmlElement(name=”XML_element_name”)

StudentParser.java

package com.javagf.parser;

import java.io.File;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import com.javagf.pojo.StudentInfo;

public class StudentParser {
 private static final String FILE_PATH = "F:\\JaxbParser\\src\\xml\\student.xml";

 public static void main(String[] args) {
 JAXBContext jContext = null;
 Unmarshaller unmarshaller = null;
 try {
 jContext = JAXBContext.newInstance(StudentInfo.class);
 unmarshaller = jContext.createUnmarshaller();
 StudentInfo sInfo = (StudentInfo) unmarshaller.unmarshal(new File(
 FILE_PATH));
 System.out.println(sInfo);
 } catch (Exception e) {
 e.printStackTrace();
 }

 }

}

Output

StudentInfo [roll=101, name=Vikash, address=Hyderabad]






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229