First, the way to get formatted XML output is to set the correct property on the marshaller (usually JAXB when working with CXF, which is good since JAXB does a commendable job). That is, somewhere you will have something like this:
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
The problem is that you do not necessarily want the entire output format to be formatted; this adds quite a bit to the overhead. Fortunately, you are already creating an explicit Response
, so we can simply use more features of this:
Marshaller marshaller = JAXBContext.newInstance(entity.getClass()).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); marshaller.marshal(entity, sw); return Response.ok(sw.toString(), MediaType.APPLICATION_XML_TYPE).build();
Another method is mentioned in this JIRA issue (itself is closed, but for you it is not much):
The workaround is to register a custom output handler that can check which user request is used to request an optional indent:
http://svn.apache.org/repos/asf/cxf/trunk/systests/jaxrs/src/test/java/org/apache/cxf/systest/jaxrs/FormatResponseHandler.java
JAXBElementProvider and JSONProvider are controlled by the JAXB marshaller, so by default they check the Marshaller.JAXB_FORMATTED_OUTPUT property on the current message.
This leads to the following code:
public class FormattedJAXBInterceptor extends AbstractPhaseInterceptor<Message> { public FormattedJAXBInterceptor() { super(Phase.PRE_STREAM); } public void handleMessage(Message message) { message.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); } public void handleFault(Message messageParam) { message.put(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); } }
The CXF website discusses registration of interceptors .