I share example JAXB.
public static <T> String convertObjectToXML(T object)
{
try {
StringWriter stringWriter = new StringWriter();
JAXBContext context = JAXBContext.newInstance( object.getClass());
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty( Marshaller.JAXB_FORMATTED_ OUTPUT, Boolean.TRUE);
marshaller.marshal(object, stringWriter);
return stringWriter.toString();
}
catch (JAXBException e){
throw new RuntimeException(String. format("Exception while marshalling: %s", e.getMessage()));
}
}
@SuppressWarnings("unchecked")
public static <T> T convertXMLToObject(Class<T> clazz, String xml)
{
try {
JAXBContext context = JAXBContext.newInstance(clazz) ;
Unmarshaller um = context.createUnmarshaller();
return (T) um.unmarshal(new StringReader(xml));
}
catch (JAXBException je){
throw new RuntimeException(String. format("Exception while Unmarshaller: %s", je.getMessage()));
}
}
public static <T> T convertXMLToObject(Class<T> clazz, InputStream file) {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
T obj = (T) jaxbUnmarshaller.unmarshal(file);
return obj;
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(String.format("Exception while Unmarshaller: %s", e.getMessage()));
}
}
No comments:
Post a Comment