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

4
我发现了这个问题,它帮助了我一些,但还不够:使用XSLT模板从一个JAXB对象转换为另一个对象 我有以下内容:
- 一个源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);
        }
    }

您可以通过以下方式实例化xsltSrc:Source xsltSrc = new StreamSource(new File(...));

1个回答

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的示例:


听起来很不错,我该怎么做呢,具体来说? - Davio
@Davio - 我添加了一个小例子。 - bdoughan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接