我需要让 XSLT 调用作为参数传递的 Java 实例上的方法。到目前为止,只有在 XSLT 本身中创建实例才能使其正常工作。如果我尝试在传递的实例上调用它,它会失败并显示
Exception in thread "main" javax.xml.transform.TransformerConfigurationException:
Cannot find external method 'Test.get' (must be public).
我可以通过输出实例来证明实例已正确传递(它以 toString 的形式出现)。这是我的 Java:
public class Test {
public static void main(String[] args) throws Exception {
Transformer transformer = TransformerFactory.newInstance()
.newTransformer(
new StreamSource(Test.class.getResourceAsStream("test.xsl")));
transformer.setParameter("test1", new Test());
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
transformer.transform(new StreamSource(
new ByteArrayInputStream(
"<?xml version=\"1.0\"?><data></data>".getBytes())),
new StreamResult(outputStream));
System.out.println(outputStream.toString());
}
public String get() {
return "hello";
}
@Override
public String toString() {
return "An instance of Test";
}
}
这是我的 xsl:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:test="xalan://Test"
exclude-result-prefixes="test"
>
<xsl:param name="test1" />
<xsl:variable name="test2" select="$test1"/>
<xsl:variable name="test3" select="test:new()"/>
<xsl:template match="/">
<data>
<!-- proves that the instance is really being passed -->
<xsl:value-of select="$test1"/>
</data>
<data>
<!-- first two do not work -->
<!--<xsl:value-of select="test:get($test1)"/>-->
<!--<xsl:value-of select="test:get($test2)"/>-->
<!-- this one does work -->
<xsl:value-of select="test:get($test3)"/>
</data>
</xsl:template>
</xsl:stylesheet>
有谁知道如何使用传递的参数使其工作?在 XSLT 中实例化它在我的实际用例中不起作用。谢谢。
最佳答案
为了让这条线正常工作:
<xsl:value-of select="test:get($test1)"/>
参数可以传递给静态函数:
class Test {
public static void get(Object context) {
// here "context" is the instance "test1"
}
...
关于java - 如何调用传递到 XSLT 的 Java 实例上的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42307273/