public class ObjectToXML {
public static void main(String args[]) {
Person person = new Person();
person.setFirtName("Aneesh");
person.setLastName("T.G");
person.setAge(25);
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// print output to console
jaxbMarshaller.marshal(person, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
use the annotation @XmlRootElement to the class you want to convert into XML.
use the annotation @XmlType propOrder for ordering the tags in the XML.
@XmlRootElement
@XmlType(propOrder={"firtName","lastName","age"})
public class Person {
private String firtName;
private String lastName;
private int age;
public String getFirtName() {
return firtName;
}
public void setFirtName(String firtName) {
this.firtName = firtName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Output
---------
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<firtName>Aneesh</firtName>
<lastName>T.G</lastName>
<age>25</age>
</person>