carlspring carlspring - 3 months ago 18
Java Question

Jersey XML indentation

I have the following code:

@Path("/search")
public class SearchRestlet
extends BaseRestlet
{

@GET
@Produces({ MediaType.APPLICATION_XML,
MediaType.APPLICATION_JSON,
MediaType.TEXT_PLAIN })
public SearchResult search(...)
throws IOException, ParseException
{
final SearchRequest searchRequest = new SearchRequest(...);
final SearchResult result = searchService.search(searchRequest);

return result;
}

}


Here's my
JAXB
mapped object:

@XmlRootElement(name = "result")
@XmlAccessorType(XmlAccessType.FIELD)
public class SearchResult
{

@XmlElement
private String id;

...

}


This is the output I get:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><result><id>foo</id></result>


This is the output I'd like to get:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<result>
<id>foo</id>
</result>


If I were using a marshaller directly, I know I can set a property for this and that it should work. How can this be done from within the context of Jersey based on the example above?

Answer

Add the following to your web.xml deployment descriptor:

<init-param>
    <param-name>jersey.config.xml.formatOutput</param-name>
    <param-value>true</param-value>
</init-param>

For more details, check MessageProperties.XML_FORMAT_OUTPUT.