convert java object into xml using jaxb


convert java object into xml using jaxb

Welcome to convert java object into xml using jaxb post, here we are going to convert java object into XML data using JAXB API.

convert java object into XML using JAXB is also known as Marshaling in java.

Convert java object into xml using jaxb example

  1. StudentInfo.java POJO class
  2. StudentParser.java for main class

StudentInfo.java

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;
 }

}

StudentParser.java

package com.javagf.parser;

import java.io.File;

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

import com.javagf.pojo.StudentInfo;

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

 public static void main(String[] args) {
 JAXBContext jContext = null;

 try {
 jContext = JAXBContext.newInstance(StudentInfo.class);

 StudentInfo sInfo = new StudentInfo();
 sInfo.setRoll(101);
 sInfo.setName("Vikas");
 sInfo.setAddress("Hyderabad");
 Marshaller marshaller = jContext.createMarshaller();
 marshaller.marshal(sInfo, new File(FILE_PATH));
 System.out.println("XML file generated in " + FILE_PATH);
 } catch (Exception e) {
 e.printStackTrace();
 }

 }

}

Output

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

 






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