@XmlRootElement to String

rest, xmlhttprequest

Solution

Use a JAXB Marshaller to convert your object to a XML-String:

JAXBContext context = JAXBContext.newInstance(Something.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter out = new StringWriter();
marshaller.marshal(something, out);
String xml = out.toString();

Problem

I'm using a class with the annotation @XmlRootElement to interact with some REST services, usually I create a javax.ws.rs.client.Entity based on this object and put it in the request body. Now one of the services doesn't require the xml object in the body but requires a xml post parameter with the utf-8 encoding of the xml object. How can I obtain the "string xml version" of the object annotated with @XmlRootElement to use it in the parameters?

Original source