Filomena
Filomena

Reputation: 29

Transform XML into string JAVA

i have this method:

public StampaModuloPrivacyResponse generaXmlALC(StampaModuloPrivacyRequest input)
        {  
        final StampaModuloPrivacyResponse stampaModuloPrivacyResponse = new StampaModuloPrivacyResponse();
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(StampaModuloPrivacyRequest.class);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(input, System.out);
            /*HERE*/
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return stampaModuloPrivacyResponse;
    } 
}

I need to transform the xml returned from marshaller in a string because i have to set in the stampamoduloPrivacyResponse.setXMLString() ...how i can do? thanks

Upvotes: 1

Views: 62

Answers (2)

davidxxx
davidxxx

Reputation: 131326

Here :

jaxbMarshaller.marshal(input, System.out);

you use the marshal(Object jaxbElement, java.io.OutputStream os ) method that accepts a outputstream and you write the xml content in the standard out.
You don't want that.

Marshaller.marshal() is overloaded and have a version that accepts a Writer.

You could so use StringWriter as Writer:

StringWriter writer = new StringWriter();
jaxbMarshaller.marshal(input, writer);
String xmlString = writer.toString();

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691625

Use a StringWriter:

StringWriter out = new StringWriter();
jaxbMarshaller.marshal(input, out);
stampamoduloPrivacyResponse.setXMLString(out.toString());

Upvotes: 0

Related Questions