Search code examples
xsltjaxbxslt-2.0mime-types

How do I read the media-type attribute from xsl output using Java EE?


I using XSLT to transform XML to other content, in this case JSON. I set the MIME using the <xsl:output method="text" media-type="application/json" encoding="UTF-8"/> tag.

I transform XML into JSON using saxon9.

Transformer transformer = tFactory.newTransformer(new StreamSource(xslUrl));
ByteArrayInputStream xmlStream = new ByteArrayInputStream(xml.getBytes());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream(baos);
transformer.transform(new StreamSource(xmlStream), new StreamResult(new OutputStreamWriter(dataOut)));
String output = baos.toString();

How can I also read the MIME as "application/json"?


Solution

  • This is the method to call to grab the MIME from the xsl:output media_type.

    String mime = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
    

    You can then act accordingly, which in my case is to setContentType for the HttpServletResponse.