Implement toString method on DOMSource when marshalling with JAXB

When serialising with JAXB to a DOMSource the object that results does not have a useful implementation of toString and alot of boiler plate is required to set up the marshalling. Here is some code that returns a DOMSource from an arbitrary JAXB annotated object with the toString method of the object return the XML representation:

public class SerialisationHelper
{
   private final String marshalledBean;
   private final Document document;
 
   private SerialisationHelper(final Object bean) throws JAXBException, ParserConfigurationException
   {
      document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
 
      final Marshaller marshaller = JAXBContext.newInstance(bean.getClass()).createMarshaller();
      marshaller.marshal(bean, document);
      final StringWriter writer = new StringWriter();
      marshaller.marshal(bean, writer);
      marshalledBean = writer.toString();
   }
 
   @Override
   public String toString()
   {
      return marshalledBean;
   }
 
   private Document toDocument()
   {
      return document;
   }
 
   public static DOMSource marshalled(final Object entity)
   {
      try
      {
         final SerialisationHelper serialisationHelper = new SerialisationHelper(entity);
         return new DOMSource(serialisationHelper.toDocument()) {
            @Override
            public String toString()
            {
               return serialisationHelper.toString();
            }};
      }
      catch (final JAXBException e)
      {
         throw new RuntimeException("unable to marshal " + entity, e);
      }
      catch (final ParserConfigurationException e)
      {
         throw new RuntimeException("unable to marshal " + entity, e);
      }
   }
}

Leave a Reply

Your email address will not be published. Required fields are marked *