I found this question that helped me a little, but not enough: Converting From one JAXB object to another using an XSLT template
What I have:
- JAXB source object
- Class for my jaxb target
- The XSLT path that I want to use to convert my source object to the target
I am trying to do this:
public static <T, U> U transformObject(final T src, final String xsltPath) {
DOMResult domRes = Marshaller.marshalObject(src);
SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
StreamSource xsltSrc = new StreamSource(xsltPath);
TransformerHandler th = tf.newTransformerHandler(xsltSrc);
th.setResult(domRes);
}
At this moment I am puzzled. How to get my converted document? From now on, of course, disconnecting it back to the JAXB object should not be too complicated.
As far as I know, there is no way to do this without sorting, right?
UPDATE
Here is a complete working example using Saxon, since my XSLT uses XSLT 2.0:
@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 create an xsltSrc instance via Source xsltSrc = new StreamSource(new File(...));