Convert one JAXB object to another using XSLT

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:

/**
 * 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 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 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:

    /**
     * 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 create an xsltSrc instance via Source xsltSrc = new StreamSource(new File(...));

+4
1

JAXBSource JAXBResult .

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

JAXB API javax.xml.transform :

+3

Source: https://habr.com/ru/post/1536781/


All Articles