如何使用带有Java对象作为参数的XML转换器?



我正在编写一个Java应用程序,其目标是进行XML转换以生成PDF文档。我使用XML文件作为输入,该文件首先解析为java对象。解析后,我想在 XML 转换中使用该对象,因此我将其设置为转换器的参数:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(new StreamSource(stylesheet));
transformer.setParameter("foo", javaObject);

该对象的实例方法在 xsl 样式表中调用,如下所示:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:pdf="http://xmlgraphics.apache.org/fop/extensions/pdf"
xmlns:MyClass="foo.bar.MyClass"
>
...
<xsl:param name="foo"/>
<xsl:param name="seller" select="MyClass:myMethod($foo)"/>

我的问题是:这是一个正确的方法吗?哪种 XSLT 处理器适合以这种方式使用参数?有没有其他方法可以做到这一点?

我尝试了Xalan(org.apache.xalan.xsltc.trax.TransformerFactoryImpl(,但我得到一个异常,找不到该方法:

ERROR:  'Cannot find external method 'foo.bar.MyClass.myMethod' (must be public).'
FATAL ERROR:  'Could not compile stylesheet'

该方法是公共的,没有参数。

对于 Saxon:有关对外部 Java 对象的"反身"调用的信息,请访问 http://www.saxonica.com/documentation/index.html#!extensibility/functions

首先要注意的是,它需要 Saxon-PE 或 -EE。

如果是没有参数的实例级(非静态(方法,则最简单的方法是:

(a( 声明与类名对应的命名空间,例如

xmlns:date="java:java.util.Date"

(b( 调用以外部对象作为第一个参数的方法:

date:getTime($date)

撒克逊人和夏兰人的机制并不相同,尽管有许多相似之处。

最新更新