java - 有条件地分配变量以匹配 xslt 模板中的路径

标签 java pdf xslt conditional-statements variable-assignment

我想在 xslt 模板中动态构建匹配。我使用 xls fo 和 apache fop 和 saxon9he。我想以最好的方式从 java 传递参数,但首先我尝试在 xslt 中设置它。

当我创建这样的变量示例时:

<xsl:variable name="testPath" select="/abc:Files/def:Description" /> 

如果我尝试在 apply-templates 中使用它,也可以正常工作:

<xsl:apply-templates select="$testPath/qwe:Test"/>

但我想动态设置 testPath 变量。我尝试使用选择标签:

<xsl:variable name="testPath"> 
    <xsl:choose>
        <xsl:when test="$versionNo = '2'">
             <xsl:value-of select="/abc:Files/def:Description" />   
        </xsl:when>
        <xsl:otherwise>
             <xsl:value-of select="/abc:Files/def:Names" /> 
        </xsl:otherwise>
    </xsl:choose>
</xsl:variable> 

但是这种方法不起作用,当我尝试使用这个变量时:

<xsl:apply-templates select="$testPath/qwe:Test"/>

我收到此错误:

Error evaluating ((attr{table-layout=...}, ...)) on line 82 column 21 of pdf_gen.xsl: SXCH0003: org.apache.fop.fo.ValidationException: "fo:table-body" is missing child elements. Required content model: marker* (table-row+|table-cell+) (See position 82:21):
file:/C:/Users/SuperUser/workspace/project/xls-editor/target/classes/pdf/xsl/pdf_gen.xsl:82:21: "fo:table-body" is missing child elements. Required content model: marker* (table-row+|table-cell+) (See position 82:21)

在最好的选择中,我想从 Java 传递 $testPath 变量作为参数,例如:

transformer.setParameter("testPath ", "/abc:Files/def:Description");

并在 xslt 中使用

<xsl:param name="testPath "/>

并在模板中应用:

<xsl:apply-templates select="$testPath/qwe:Test"/>

但我收到以下错误:

Type error evaluating ($testPath) in xsl:apply-templates/@select on line 74 column 60 of pdf_gen.xsl: XPTY0019: The required item type of the first operand of '/' is node(); the supplied value
u"/abc:Files/def:Description" is an atomic value

为什么没有任何解决方案可以实现它?

最佳答案

当您使用 Saxon 9 时,您至少使用 XSLT 2 和 XPath 2,我建议在 XPath 中实现变量选择,例如

<xsl:variable name="testPath" select="if ($versionNo = '2') then /abc:Files/def:Description else /abc:Files/def:Names"/> 

这样你的

<xsl:apply-templates select="$testPath/qwe:Test"/>

应该可以正常处理先前选择的 def:Descriptiondef:Names 元素的 qwe:Test 子元素.

当然也可以使用例如

<xsl:apply-templates select="(if ($versionNo = '2') then /abc:Files/def:Description else /abc:Files/def:Names)/qwe:Test"/>

或者做例如

<xsl:apply-templates select="(/abc:Files/def:Description[$versionNo = '2'], /abc:Files/def:Names[$versionNo != '2'])/qwe:Test"/>

关于java - 有条件地分配变量以匹配 xslt 模板中的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54345270/

相关文章:

java - 并行执行 TestNG 测试,一个浏览器不会关闭

java - 如何在不使用包的情况下识别给定路径是Java中的文件还是目录?

java - 有没有办法强制执行finalize()方法

html - Apache FOP 可以用于将任意 HTML 转换为 PDF 吗?

java - 水平分割 PDF 的一部分

java - 如何让 XSLT 在输出数值运算结果时停止使用科学记数法?

java - 为什么 Java 编译器允许在三元运算符中将 null 转换为原始类型

c# - Internet Explorer PDF 阅读器

xslt - 如何使用 XSLT 向 XML 负载添加不同的 namespace

java - XSLT/Java : ERROR: 'Cannot find external method ' max' (must be public). '