This blog explains about converting POJO(Plain Old Java Object) to XML and XML to POJO
- Below is the EmployeeDTO, Ensure to specify @XMLRootElement
- Below is the XMLUtil class
Note : Have jaxb-api-2.2.jar on class path
- Below is the EmployeeDTO, Ensure to specify @XMLRootElement
package com.fm.xmlutil.dto;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class EmployeeDTO {
public EmployeeDTO() {
super();
}
private String fName;
private String lName;
private String address1;
public void setFName(String fName) {
this.fName = fName;
}
public String getFName() {
return fName;
}
public void setLName(String lName) {
this.lName = lName;
}
public String getLName() {
return lName;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress1() {
return address1;
}
}
- Below is the XMLUtil class
package com.fm.xmlutil;
import com.fm.xmlutil.dto.EmployeeDTO;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
/**
* This class has the util methods to convert the POJOs to XML and vice versa using JAXB API.
*
* @author Fortune Minds
*/
public class XMLUtil {
/**
*This methodd converts Java Object to XML String
* @param rootObject
* @return
* @throws Exception
*/
public static String javaToXml(Object rootObject) throws Exception {
StringWriter writer = new StringWriter();
JAXBContext jaxbContext =
JAXBContext.newInstance(rootObject.getClass());
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(rootObject, writer);
return writer.toString();
}
/**
* This method converts XML to Java Object
* @param rootObject
* @param xmlString
* @return
* @throws Exception
*/
public static Object xmlToJava(Object rootObject,
String xmlString) throws Exception {
JAXBContext jaxbContext =
JAXBContext.newInstance(rootObject.getClass());
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return jaxbUnmarshaller.unmarshal(new StringReader(xmlString));
}
public static void main(String args[]){
EmployeeDTO dto = new EmployeeDTO();
dto.setFName("FortuneMinds");
dto.setLName("Inc");
dto.setAddress1("8000 Corporatecenter Drive");
try {
String r =javaToXml(dto);
System.out.println(r);
} catch (Exception e) {
// TODO: Add catch code
e.printStackTrace();
}
}
}
Note : Have jaxb-api-2.2.jar on class path
No comments:
Post a Comment