Java examples for XML:JAXB
get XML From Object via JAXB
//package com.java2s; import java.io.ByteArrayOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; public class Main { public static void main(String[] argv) throws Exception { Object objJAXB = "java2s.com"; System.out.println(getXMLFromObject(objJAXB)); }/*from w ww. j a v a 2 s .c o m*/ public static String getXMLFromObject(Object objJAXB) throws Exception { return marshal(objJAXB); } private static String marshal(Object objJAXB) throws Exception { ByteArrayOutputStream result = new ByteArrayOutputStream(); newMarshaller(objJAXB.getClass()).marshal(objJAXB, newWriter(result)); return result.toString(); } private static Marshaller newMarshaller(Class<?> classJAXB) throws Exception { return newContext(classJAXB).createMarshaller(); } private static XMLStreamWriter newWriter(ByteArrayOutputStream result) throws Exception { XMLOutputFactory output = XMLOutputFactory.newInstance(); XMLStreamWriter writer = output.createXMLStreamWriter(result); return writer; } private static JAXBContext newContext(Class<?> classJAXB) throws Exception { return JAXBContext.newInstance(classJAXB); } }