java – 使用XSLT将一个JAXB对象转换为另一个JAXB对象
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 使用XSLT将一个JAXB对象转换为另一个JAXB对象,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2388字,纯文字阅读大概需要4分钟。
内容图文
![java – 使用XSLT将一个JAXB对象转换为另一个JAXB对象](/upload/InfoBanner/zyjiaocheng/786/f5e61b27390d46a6bd4fc79ffcf1860f.jpg)
我发现了这个问题,这对我有所帮助,但还不够: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对象应该不会太难.
据我所知,没有编组就没办法做到这一点,对吧?
UPDATE
这是一个完整的工作示例,特别是使用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;
解决方法:
您可以直接使用JAXBSource和JAXBResult进行转换.
JAXBSource source = new JAXBSource(marshaller, src);
JAXBResult result = new JAXBResult(jaxbContext);
transformer.transform(source, result);
Object result = result.getResult();
欲获得更多信息
您可以在我的博客上找到使用JAXB和javax.xml.transform API的示例:
> http://blog.bdoughan.com/2012/11/using-jaxb-with-xslt-to-produce-html.html
内容总结
以上是互联网集市为您收集整理的java – 使用XSLT将一个JAXB对象转换为另一个JAXB对象全部内容,希望文章能够帮你解决java – 使用XSLT将一个JAXB对象转换为另一个JAXB对象所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。