Convert Java object to XML string

A convenient option is to use javax.xml.bind.JAXB:

StringWriter sw = new StringWriter();
JAXB.marshal(customer, sw);
String xmlString = sw.toString();

The [reverse] process (unmarshal) would be:

Customer customer = JAXB.unmarshal(new StringReader(xmlString), Customer.class);

No need to deal with checked exceptions in this approach.


You can use the Marshaler's method for marshaling which takes a Writer as parameter:

marshal(Object,Writer)

and pass it an Implementation which can build a String object

Direct Known Subclasses: BufferedWriter, CharArrayWriter, FilterWriter, OutputStreamWriter, PipedWriter, PrintWriter, StringWriter

Call its toString method to get the actual String value.

So doing:

StringWriter sw = new StringWriter();
jaxbMarshaller.marshal(customer, sw);
String xmlString = sw.toString();

Tags:

Java

Xml

Jaxb