Reputation: 2348
I want to populate all the xml
data to java bean class,
<employee>
<empId>a01</empId>
<dptName>dev</dptName>
<person>
<name>xyz</name>
<age>30</age>
<phone>123456</phone>
</person>
</employee>
Below is the java bean class in which i want to store the xml
data.
class employee{
private String empId;
private String dptName;
private Person person;
//getter setter below
}
class Person{
String name;
private String age;
private String phone;
//getter setter below
}
I think this can be done using JAXB
but how ?
Note : further i have to save the data into data base.
Upvotes: 1
Views: 4943
Reputation: 149047
Without any annotations you could do the following with JAXB (JSR-222) which is included in the JDK/JRE since Java SE 6:
Your model appears to match all the default naming rules necessary to map to the XML that you have posted. This means that you can use your model without adding any metadata in the form of annotations. One thing to note is that if you don't specify metadata to associate root elements with classes then you need to specify a Class
parameter when unmarshalling and wrap the root object in an instance of JAXBElement
when marshalling.
Demo
In the demo code below we will convert the XML to objects and then convert the objects back to XML.
JAXBContext jc = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
JAXBElement<Employee> je = unmarshaller.unmarshal(xml, Employee.class);
Employee employee = je.getValue();
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(je, System.out);
For More Information
JAXBElement
with @XmlRootElement
When a class is associated with a root element using @XmlRootElement
(or @XmlElementDecl
) then you don't need to specify the Class
parameter when unmarshalling or wrap the result in a JAXBElement
when marshalling.
Employee
@XmlRootElement
class Employee {
Demo
JAXBContext jc = JAXBContext.newInstance(Employee.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
Employee employee = (Employee) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(employee, System.out);
For More Information
Upvotes: 5
Reputation: 4274
You can do this thing easily with the xstream api
XStream is a simple library to serialize objects to XML and back again.
Here you will find documentation XStream Core 1.4.5-SNAPSHOT documentation
Upvotes: -2