package com.doj.jaxb; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * @author Dinesh Rajput * */ @XmlRootElement public class Employee { private int empid; private String name; private float salary; private String address; @XmlAttribute public int getEmpid() { return empid; } public void setEmpid(int empid) { this.empid = empid; } @XmlElement public String getName() { return name; } public void setName(String name) { this.name = name; } @XmlElement public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } @XmlElement public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
package com.doj.jaxb; import java.io.FileNotFoundException; import java.io.FileOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; /** * @author Dinesh Rajput * */ public class ObjectToXMLTest { /** * @param args * @throws JAXBException * @throws FileNotFoundException */ public static void main(String[] args) throws JAXBException, FileNotFoundException { JAXBContext contextObj = JAXBContext.newInstance(Employee.class); Marshaller marshallerObj = contextObj.createMarshaller(); marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); Employee emp = new Employee(); emp.setEmpid(1111); emp.setName("Dinesh Rajput"); emp.setSalary(100000); emp.setAddress("Noida"); marshallerObj.marshal(emp, new FileOutputStream("employee.xml")); } }Run this application as java program lets see following output file in application
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <employee empid="1111"> <address>Noida</address> <name>Dinesh Rajput</name> <salary>100000.0</salary> </employee>
Labels: JAXB