Getting Marshall result into String

JavaJaxb

Java 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSunny GuptaView Question on Stackoverflow
Solution 1 - JavaRadouane ROUFIDView Answer on Stackoverflow
Solution 2 - JavaSunny GuptaView Answer on Stackoverflow
Solution 3 - JavalazView Answer on Stackoverflow