如何使用带有 Java 对象作为参数的 XML 转换器? [英] How to use XML transformer with Java object as parameter?
问题描述
我正在编写一个 Java 应用程序,其目标是进行 XML 转换以生成 PDF 文档.我使用一个 XML 文件作为输入,它首先被解析为一个 java 对象.解析后我想在 XML 转换中使用该对象,因此我将其设置为转换器的参数:
I'm writing a Java application, where the goal is to do XML transformation to generate a PDF document. I'm using an XML file as input, which is first parsed to a java object. After parsing I want to use that object in the XML transformation, so I set it as a parameter for the transformer:
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer(new StreamSource(stylesheet));
transformer.setParameter("foo", javaObject);
在 xsl 样式表中调用该对象的实例方法,如下所示:
An instance method of that object is called in the xsl stylesheet like this:
<?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 处理器适合以这种方式使用参数?还有其他方法吗?
My question is: is this a proper way to do this? Which XSLT processor is suitable for using parameters this way? Is there another way to do it?
我尝试了 Xalan (org.apache.xalan.xsltc.trax.TransformerFactoryImpl),但我得到一个无法找到该方法的异常:
I tried out Xalan (org.apache.xalan.xsltc.trax.TransformerFactoryImpl) but I get an Exception that the method cannot be found:
ERROR: 'Cannot find external method 'foo.bar.MyClass.myMethod' (must be public).'
FATAL ERROR: 'Could not compile stylesheet'
该方法是公共的,没有参数.
The method is public and has no arguments.
推荐答案
对于 Saxon:可以在 http://www.saxonica.com/documentation/index.html#!extensibility/functions
For Saxon: Information on "reflexive" calls to external Java objects can be found at http://www.saxonica.com/documentation/index.html#!extensibility/functions
首先要注意的是它需要 Saxon-PE 或 -EE.
The first thing to note is that it requires Saxon-PE or -EE.
如果是没有参数的实例级(非静态)方法,那么最简单的方法是:
If it's an instance-level (non-static) method with no parameters, then the simplest approach is:
(a) 声明一个与类名对应的命名空间,例如
(a) declare a namespace corresponding to the class name, for example
xmlns:date="java:java.util.Date"
(b) 以外部对象作为第一个参数调用方法:
(b) call the method with the external object as the first argument:
date:getTime($date)
撒克逊人和夏兰人的机制并不相同,但有许多相似之处.
The Saxon and Xalan mechanisms are not identical, though there are many similarities.
这篇关于如何使用带有 Java 对象作为参数的 XML 转换器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!