Java 中带参数的 XSL 转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1667454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 18:56:15  来源:igfitidea点击:

XSL Transformation in Java with parameters

javaxslt

提问by Anirudh

I have a xsl file where i need to use parameters from an external source. I am using Java and my code looks something like this:

我有一个 xsl 文件,我需要在其中使用来自外部源的参数。我正在使用 Java,我的代码如下所示:

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer xsltTransformer = transformerFactory.newTransformer(xsltSource);
xsltTransformer.setParameter(parameterName, parameterValue);

However, an exception is thrown at the 2nd line - Variable or parameter 'variable_name' is undefined.I realize that XSL is compiled and is probably compiled when the transformer is created.

但是,在第 2 行抛出异常 -变量或参数“variable_name”未定义。我意识到 XSL 已编译,并且可能在创建转换器时编译。

So, how do i pass parameters to my transformation? How is the setParameter method supposed to be used?

那么,我如何将参数传递给我的转换?应该如何使用 setParameter 方法?

采纳答案by rsp

If you pass a parameter like:

如果传递如下参数:

transformer.setParameter("render_id", "1234");

the parameter can be picked up by the transform:

参数可以通过变换获取:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform" >

<xsl:output method="xml" encoding="UTF-8" omit-xml-declaration="yes"/>

<!-- Receives the id of the menu being rendered. -->
<xsl:param name="render_id" />

回答by TinyRacoon

rsp's answer was spot on. Thanks. Just want to add that you cannot pass a parameter to a variable in the same way (I am setting parameters via Java's TransformerFactory).

rsp 的回答是正确的。谢谢。只是想补充一点,您不能以相同的方式将参数传递给变量(我正在通过 Java 的 TransformerFactory 设置参数)。

I made the mistake of thinking variables and params were interchangeable :)

我错误地认为变量和参数是可以互换的:)