I took the JAXB.marshal implementation and added jaxb.fragment=true to remove the XML prolog. This method can handle objects even without the XmlRootElement annotation. This also throws the 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 the compiler warning bothers you, here's the templated, two parameter version.
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);
}
}