XML marshalling

This is a Post To convert a Xml file to java Object and back to XML

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

public class Main {
public static void main(String[] args) {

try {
Employee employee = new Employee();
employee.setName("Kowthal ganesh");
employee.setAge(23);
employee.setDepartment("Chola-ccms");
employee.setId("947");
employee.setSalary(8333);
Job child = new Job();
child.setName("sanjoy");
child.setSalary(9000);
employee.setChild(child);
File file = new File("D:/build.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(employee, file);

JAXBContext jc = JAXBContext.newInstance(Employee.class);
            Unmarshaller u = jc.createUnmarshaller();

            File f = new File("D:/build.xml");
            Employee employee1 = (Employee) u.unmarshal(f);
            System.out.println("Employee Name : "+employee1.getChild().getName());
} catch (Exception ert) {
}
}

}


import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Employee {
private String name;
private String id;
private String department;
private int age;
private int salary;
private Job child;

public String getName() {
return name;
}

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

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

public int getAge() {
return age;
}

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

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}

/**
* @return the child
*/
public Job getChild() {
return child;
}

/**
* @param child the child to set
*/
public void setChild(Job child) {
this.child = child;
}
}


public class Job {

private String  name;
private int salary;
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the salary
*/
public int getSalary() {
return salary;
}
/**
* @param salary the salary to set
*/
public void setSalary(int salary) {
this.salary = salary;
}
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

Reactions

Post a Comment

0 Comments