如何在Apache FOP中利用XSLT获取property节点属性实现URL的条件格式化?
在Apache FOP中基于property节点的type属性实现URL条件格式化
你的问题核心是对XSLT的节点上下文理解有误:当模板匹配property节点时,当前处理的上下文就是该property节点本身,所以你完全可以直接访问它的type属性来做条件判断。下面是修正后的完整解决方案:
修正后的XSLT代码
<xsl:template name="table-row"> <xsl:for-each select="properties/property"> <xsl:apply-templates select="."/> </xsl:for-each> </xsl:template> <xsl:template match="property"> <fo:table-cell> <fo:block> <xsl:choose> <!-- 直接判断当前property节点的type属性是否为HYPERLINK --> <xsl:when test="@type='HYPERLINK'"> <!-- 拆分value中的链接文本和URL(按=分隔) --> <fo:basic-link external-destination="{substring-after(value, '=')}"> <xsl:value-of select="substring-before(value, '=')"/> </fo:basic-link> </xsl:when> <xsl:otherwise> <!-- 普通文本直接输出value内容 --> <xsl:value-of select="value"/> </xsl:otherwise> </xsl:choose> </fo:block> </fo:table-cell> </xsl:template>
关键细节说明
- 条件判断逻辑:
test="@type='HYPERLINK'"直接引用当前property节点的type属性,因为模板匹配的就是property,上下文完全正确,不需要额外获取节点。 - HYPERLINK节点处理:针对你示例中
value的格式(文本=URL),用substring-before和substring-after拆分内容,然后通过Apache FOP的fo:basic-link标签生成可点击的外部链接,external-destination属性指定跳转的URL。 - 普通节点处理:非HYPERLINK类型的节点直接输出
value的文本内容,保持原有格式。
效果验证
针对你提供的XML示例中的HYPERLINK节点:
<property type="HYPERLINK" key="ASSET_LINK"> <name>Asset Link</name> <value>Test=https://test.com</value> </property>
转换后会生成对应的FO链接代码,最终在PDF中显示为可点击的“Test”链接,点击后跳转到https://test.com。
内容的提问来源于stack exchange,提问作者Pramod
相关产品推荐
相关产品推荐

