Java tutorial
//package com.java2s; import java.beans.XMLEncoder; import java.io.ByteArrayOutputStream; import java.io.OutputStream; public class Main { /*** * Serialize an object into xml string. * * @param obj * object to serialize * @return Xml string represents the object */ public static String serializeObject(final Object obj) { final OutputStream bufferStream = new ByteArrayOutputStream(); // Create XML encoder. final XMLEncoder xenc = new XMLEncoder(bufferStream); xenc.writeObject(obj); // Need to close the XMLEncoder to flush. xenc.close(); final String serializedString = bufferStream.toString(); // JavaDoc indicates that we will not need to close // a ByteArrayOutputStream. From JavaDoc: // Closing a ByteArrayOutputStream has no effect. The methods // in this class can be called after the stream has been closed // without generating an IOException. // // bufferStream.close(); return serializedString; } }