Getting Marshall result into String
JavaJaxbJava Problem Overview
JAXBContext context = JAXBContext
.newInstance(CreateExemptionCertificate.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
m.marshal(cc, System.out);
In the code above i am getting the result to the console (I mean XML is getting printed on the console). I want to get this XML to a string. I am not getting which argument I should pass to the marshal method to get XML String in a String variable instead of printing it on the console. Anybody having any idea please share.
Java Solutions
Solution 1 - Java
You can do it like this :
CreateExemptionCertificate cc = ...;
JAXBContext context = JAXBContext.newInstance(CreateExemptionCertificate.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
StringWriter sw = new StringWriter();
m.marshal(cc, sw);
String result = sw.toString();
Solution 2 - Java
Just now I have got the answer of my question from this post below:
https://stackoverflow.com/questions/2472155/i-want-to-convert-an-output-stream-into-string-object
I need to use StringWriter to take XML String from Marshal method
Solution 3 - Java
Try marshalling to an instance of ByteArrayOutputStream
and then invoking toByteArray
on it.