Java tutorial
//package com.java2s; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class Main { /** * this method is responsible for converting any pojo to respective xml form * * @param object * @param filePath * @throws JAXBException * @throws IOException */ public static File pojoToXml(Object object, String filePath) throws JAXBException, IOException { JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); OutputStream os = new FileOutputStream(filePath); marshaller.marshal(object, os); File file = new File(filePath); return file; } /** * * @param object * @return * @throws JAXBException */ public static String pojoToXml(Object object) throws JAXBException { JAXBContext context = JAXBContext.newInstance(object.getClass()); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // marshaller.setProperty(Marshaller.JAXB_ENCODING, "U"); StringWriter writer = new StringWriter(); marshaller.marshal(object, writer); String xmlData = writer.toString(); return xmlData; } }