Java tutorial
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.Marshaller; import javax.xml.namespace.QName; public class Main { /** * Utility method to marshal a JAXB annotated java object to an XML * formatted string. This class is generic enough to be used for any * JAXB annotated java object not containing the {@link XmlRootElement} * annotation. * * @param xmlClass The JAXB class of the object to marshal. * @param xmlObject The JAXB object to marshal. * @return String containing the XML encoded object. */ public static String jaxbToString(Class<?> xmlClass, Object xmlObject) { // Make sure we are given the correct input. if (xmlClass == null || xmlObject == null) { return null; } @SuppressWarnings("unchecked") JAXBElement<?> jaxbElement = new JAXBElement(new QName("uri", "local"), xmlClass, xmlObject); return jaxbToString(xmlClass, jaxbElement); } public static String jaxbToString(Class<?> xmlClass, JAXBElement<?> jaxbElement) { // Make sure we are given the correct input. if (xmlClass == null || jaxbElement == null) { return null; } // We will write the XML encoding into a string. StringWriter writer = new StringWriter(); String result; try { // We will use JAXB to marshal the java objects. final JAXBContext jaxbContext = JAXBContext.newInstance(xmlClass); // Marshal the object. Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jaxbMarshaller.marshal(jaxbElement, writer); result = writer.toString(); } catch (Exception e) { // Something went wrong so get out of here. return null; } finally { try { writer.close(); } catch (IOException ex) { } } // Return the XML string. return result; } }