Marshalling Example
File: com.ram.core.Person.java
package com.ram.core;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Person {
private String name;
private int id;
private int age;
private String address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
File: com.ram.core.MarshallExample.java
package com.ram.core;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
public class MarshallExample {
public static void main(String[] args){
try{
Person person = new Person();
person.setName("Ram");
person.setId(1);
person.setAge(31);
person.setAddress("Richmond");
JAXBContext jaxbContext = JAXBContext.newInstance(Person.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
File file = new File("C:\\Person.xml");
jaxbMarshaller.marshal(person, file);
jaxbMarshaller.marshal(person, System.out);
}catch(Exception e){
System.out.println("Exception while marshalling ..."+e);
}
}
}
Below is the output file that gets generated when the above program is executed
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<person>
<address>Richmond</address>
<age>31</age>
<id>1</id>
<name>Ram</name>
</person>
No comments:
Post a Comment