Pretty Print XML and JAXB Marshalling/Unmarshalling

Posted by & filed under Uncategorized.

I always seem to forget how to print XML with pretty-print enabled.   A quick google search reveals that there are a few third party libaries, XOM and JDom.  If you want to use a method that comes with the JDK using the included apache library, here is how you do it.

  public void marshalAndPrettyPrintTest() throws Exception
  {
      final JAXBContext jc = JAXBContext.newInstance(SomeRootClass.class);
      final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      final Marshaller marshaller = jc.createMarshaller();

      final Transformer serializer = TransformerFactory.newInstance().newTransformer();
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      marshaller.marshal(mockSomeRootClass(), doc);
      serializer.transform(new DOMSource(doc), new StreamResult(System.out));
  }

JAXB is inheritly slow during initialization.  One way I found to speed this up is to cache the JAXBContext using a simple Hashtable.  JAXBContext is thread safe.