Transforming one JAXB Object to another using XSLT

java, jaxb, xml, xslt

Solution

You could use `JAXBSource` and `JAXBResult` directly with your transformation.

JAXBSource source = new JAXBSource(marshaller, src);
JAXBResult result = new JAXBResult(jaxbContext);
transformer.transform(source, result);
Object result = result.getResult();

For More Information

You can find an example of using JAXB with the `javax.xml.transform` APIs on my blog:

- http://blog.bdoughan.com/2012/11/using-jaxb-with-xslt-to-produce-html.html

Problem

I found this question, which helped me a bit, but not enough: Transform From one JAXB object to another using XSLT template What I have is this: - A source JAXB Object - A class for my target JAXB Object - A path to the XSLT I want to use to transform my original object to my target object What I'm trying is this: ``` /** * Transforms one JAXB object into another with XSLT * @param src The source object to transform * @param xsltPath Path to the XSLT file to use for transformation * @return The transformed object */ public static <T, U> U transformObject(final T src, final String xsltPath) { // Transform the JAXB object to another JAXB object with XSLT, it's magic! // Marshal the original JAXBObject to a DOMResult DOMResult domRes = Marshaller.marshalObject(src); // Do something here SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); StreamSource xsltSrc = new StreamSource(xsltPath); TransformerHandler th = tf.newTransformerHandler(xsltSrc); th.setResult(domRes); } ``` At this point, I'm puzzled. How do I obtain my transformed Document? From that point, unmarshalling it back to a JAXB object shouldn't be too hard, I think. As far as I know, there's no way to do this without marshalling, right? UPDATE Here is a full working example, using Saxon specifically as my XSLT's are using XSLT 2.0: ``` /** * Transforms one JAXB object into another with an XSLT Source * * @param src * The source (JAXB)object to transform * @param xsltSrc * Source of the XSLT to use for transformation * @return The transformed (JAXB)object */ @SuppressWarnings("unchecked") public static <T, U> U transformObject(final T src, final Source xsltSrc, final Class<U> clazz) { try { final JAXBSource jxSrc = new JAXBSource(JAXBContext.newInstance(src.getClass()), src); final TransformerFactory tf = new net.sf.saxon.TransformerFactoryImpl(); final Transformer t = tf.newTransformer(xsltSrc); final JAXBResult jxRes = new JAXBResult(JAXBContext.newInstance(clazz)); t.transform(jxSrc, jxRes); final U res = (U) jxRes.getResult(); return res; } catch (JAXBException | TransformerException e) { e.printStackTrace(); throw new RuntimeException(e); } } ``` You can instantiate the xsltSrc through `Source xsltSrc = new StreamSource(new File(...));`

Original source