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: C:\Person.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <person> <address>Richmond</address> <age>31</age> <id>1</id> <name>Ram</name> </person>
File: com.ram.core.UnmarshallExample.java
package com.ram.core; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.Unmarshaller; public class UnmarshallExample { public static void main(String[] args) { try{ JAXBContext jaxbContext = JAXBContext.newInstance(Person.class); Unmarshaller unmarshall = jaxbContext.createUnmarshaller(); File f = new File("C:\\Person.xml"); Person person = (Person) unmarshall.unmarshal(f); System.out.println("Name = "+person.getName()); System.out.println("Id = "+person.getId()); System.out.println("Age = "+person.getAge()); System.out.println("Address = "+person.getAddress()); }catch(Exception e){ System.out.println("Exception occurred while unmarshalling ..."+e); } } }
Below is the output file that gets generated when the above program is executed
Name = Ram
Id = 1
Age = 31
Address = Richmond
Name = Ram
Id = 1
Age = 31
Address = Richmond
No comments:
Post a Comment