60
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,929
  • 15
  • 52
  • 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

4 Answers4

81

You can do it like this :

CreateExemptionCertificate cc = ...;
JAXBContext context = JAXBContext.newInstance(CreateExemptionCertificate.class);
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

StringWriter sw = new StringWriter();
m.marshal(cc, sw);

String result = sw.toString();
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
Radouane ROUFID
  • 10,595
  • 9
  • 42
  • 80
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,929
  • 15
  • 52
  • 80
7

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

laz
  • 28,320
  • 5
  • 53
  • 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
0

This is the parser I use for convert an object to string using jaxb library.

 JAXBElement<Foo> jaxbElement = new JAXBElement<>(
                new QName(Foo.class.getSimpleName()), Foo.class, request);
        JAXBContext contextRS = JAXBContext.newInstance(Foo.class);
        String requestXml = lhParser.marshalAndConvertToString(jaxbElement, contextRS);


//converter

    public String marshalAndConvertToString(JAXBElement jaxbElement, JAXBContext context) {
        try {
            StringWriter writer = new StringWriter();
            context.createMarshaller().marshal(jaxbElement, writer);
            String s = writer.toString();
            LOG.info(" ------------------------ xml \n{}",s );
            return s;
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }