Skip to content

Instantly share code, notes, and snippets.

@achyutdev
Created September 22, 2016 15:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achyutdev/9a0884194ca589c8eb91c870da7e2d49 to your computer and use it in GitHub Desktop.
Save achyutdev/9a0884194ca589c8eb91c870da7e2d49 to your computer and use it in GitHub Desktop.
package application;
import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import domain.Address;
import domain.Student;
public class Application {
private static final String FILE_NAME = "jaxb-student.xml";
public static void main(String... strings) {
Student std = new Student();
std.setAddress(new Address("Amity Moor Rd", "Westerville", "43081"));
std.setId(1);
std.setName("Achyut Devkota");
std.setTransitent("Nothing");
jaxbObjectToXml(std);
Student stuFromFile = jaxbXMLToObject();
System.out.println(stuFromFile);
}
private static Student jaxbXMLToObject() {
try {
JAXBContext context = JAXBContext.newInstance(Student.class);
Unmarshaller un = context.createUnmarshaller();
Student emp = (Student) un.unmarshal(new File(FILE_NAME));
return emp;
} catch (JAXBException e) {
e.printStackTrace();
}
return null;
}
private static void jaxbObjectToXml(Student std) {
try {
JAXBContext context = JAXBContext.newInstance(Student.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(std, new File(FILE_NAME));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment