Feeding marshalled JAXB data to Jersey
Although Jersey supports eating JAXB’ed classes fine, sometimes you want to manually alter the data, such as including a processing instruction for XSL stylesheets. There probably should be a less verbose way to do this.
The object should be an @XMLRootElement
annotated object.
@GET
@Produces("application/xml")
public static StreamingOutput outputXMLwithXSL() {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException,
WebApplicationException {
Object object = yourJAXBObject();
JAXBContext jc = null;
try { jc = JAXBContext.newInstance(object.getClass()); }
catch (JAXBException e) { e.printStackTrace(); }
Marshaller m = null;
try { m = jc.createMarshaller(); }
catch (JAXBException e) { e.printStackTrace(); }
PrintStream ps = new PrintStream(output);
ps.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
ps.println("<?xml-stylesheet type=\"text/xsl\" href=\"your.xsl\"?>");
try { m.setProperty(Marshaller.JAXB_FRAGMENT, true); }
catch (PropertyException e) { e.printStackTrace(); }
try { m.marshal(object, output); }
catch (JAXBException e) { e.printStackTrace(); }
}
};
}