Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@XmlRootElement to String

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?

like image 964
Cattani Simone Avatar asked Jan 11 '23 12:01

Cattani Simone


1 Answers

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();
like image 141
lefloh Avatar answered Jan 25 '23 15:01

lefloh