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

Sunny Gupta
  • 6,609
  • 15
  • 50
  • 80
  • possible duplicate of [I want to convert an output stream into String object](http://stackoverflow.com/questions/2472155/i-want-to-convert-an-output-stream-into-string-object) – nbrooks Feb 25 '15 at 18:30

3 Answers3

69

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();
Radouane ROUFID
  • 10,059
  • 9
  • 37
  • 76
26

Just now I have got the answer of my question from this post below:

I want to convert an output stream into String object

I need to use StringWriter to take XML String from Marshal method

Community
  • 1
  • 1
Sunny Gupta
  • 6,609
  • 15
  • 50
  • 80
6

Try marshalling to an instance of ByteArrayOutputStream and then invoking toByteArray on it.

laz
  • 27,919
  • 5
  • 52
  • 50
  • What do you want to do with it? The approach I proposed (calling `toByteArray()` on the stream) would give you a `byte[]` instance containing the bytes of the XML. – laz Feb 06 '12 at 06:08
  • Im having the same need, in my case I'm trying to returning it as a result of service call. – code4jhon Nov 10 '13 at 21:09