使用XSLT将一个JAXB对象转换为另一个JAXB对象

时间:2014-04-16 12:59:44

标签: java xml xslt jaxb

我发现了这个问题,这对我有所帮助,但还不够:Transform From one JAXB object to another using XSLT template

我拥有的是:

  • 源JAXB对象
  • 我的目标JAXB对象的类
  • 我想用来将原始对象转换为目标对象的XSLT路径

我正在尝试的是:

/**
 * 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);
}

此时,我很困惑。我如何获得转换后的文档?从那时起,我认为将它解组回JAXB对象应该不会太难。

据我所知,没有编组就没办法做到这一点,对吗?

更新

这是一个完整的工作示例,特别是使用Saxon,因为我的XSLT正在使用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);
        }
    }

您可以通过Source xsltSrc = new StreamSource(new File(...));

实例化xsltSrc

1 个答案:

答案 0 :(得分:3)

您可以直接使用JAXBSourceJAXBResult进行转换。

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

了解更多信息

您可以在我的博客上找到使用JAXB和javax.xml.transform API的示例: