I took the implementation of JAXB.marshal and added jaxb.fragment = true to remove the XML prolog. This method can process objects even without an XmlRootElement annotation. This also raises an unchecked DataBindingException.
public static String toXmlString(Object o) { try { Class<?> clazz = o.getClass(); JAXBContext context = JAXBContext.newInstance(clazz); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // remove xml prolog marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // formatted output final QName name = new QName(Introspector.decapitalize(clazz.getSimpleName())); JAXBElement jaxbElement = new JAXBElement(name, clazz, o); StringWriter sw = new StringWriter(); marshaller.marshal(jaxbElement, sw); return sw.toString(); } catch (JAXBException e) { throw new DataBindingException(e); } }
If you are worried about the compiler warning, then here is the template version with two parameters.
public static <T> String toXmlString(T o, Class<T> clazz) { try { JAXBContext context = JAXBContext.newInstance(clazz); Marshaller marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // remove xml prolog marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // formatted output QName name = new QName(Introspector.decapitalize(clazz.getSimpleName())); JAXBElement jaxbElement = new JAXBElement<>(name, clazz, o); StringWriter sw = new StringWriter(); marshaller.marshal(jaxbElement, sw); return sw.toString(); } catch (JAXBException e) { throw new DataBindingException(e); } }
Bienvenido David Mar 26 '19 at 22:54 2019-03-26 22:54
source share