我发现了这个问题,它帮助了我一些,但还不够:使用XSLT模板从一个JAXB对象转换为另一个对象
我有以下内容:
- 一个源JAXB对象 - 用于我的目标JAXB对象的类 - 一个我想要使用的XSLT路径,以将原始对象转换为目标对象
我正在尝试的是:
- 一个源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(...));