如何在Python中通过saxonche向XSLT 2.0传递参数
解决SaxonC Python传递XSLT参数的问题
问题背景
成功执行pip install saxonche后,可通过Python调用SaxonC实现XSLT转换。现有XSLT脚本定义了my_param1和my_param2两个参数,但原Python代码未实现参数传递逻辑,导致转换后HTML输出缺失参数值(实际输出为Hello world! | |,预期为Hello world! | value1 | value2)。
环境信息
- Python v3.12.4
- Saxonica官方saxonche包(SaxonC-HE 12.5.0):支持XSLT 3.0、XQuery 3.1、XPath 3.1及XML Schema处理
- Win10
修改后的Python代码
from saxonche import * output_file = 'output.html' with PySaxonProcessor(license=False) as proc: print(proc.version) try: xsltproc = proc.new_xslt30_processor() document = proc.parse_xml(xml_file_name='input.xml') executable = xsltproc.compile_stylesheet(stylesheet_file="xslt2.xsl") # 传递XSLT参数:将Python字符串转换为SaxonC的XDM值类型 executable.set_parameter("my_param1", proc.make_string_value("value1")) executable.set_parameter("my_param2", proc.make_string_value("value2")) output = executable.transform_to_string(xdm_node=document) print(output) with open(output_file, 'wb') as f: f.write(output.encode('utf-8')) except PySaxonApiError as err: print('Error during function call', err)
关键修改说明
SaxonC的API要求传递给XSLT的参数必须是XDM数据类型,不能直接传入Python原生字符串,因此需要:
- 调用
proc.make_string_value()将Python字符串转换为XdmString对象; - 通过
executable.set_parameter()方法绑定XSLT参数名与对应的值; - 也可通过
transform_to_string()的parameters参数传递字典实现批量参数设置(示例如下):
# 批量传递参数的替代写法 params = { "my_param1": proc.make_string_value("value1"), "my_param2": proc.make_string_value("value2") } output = executable.transform_to_string(xdm_node=document, parameters=params)
验证结果
修改后执行代码,输出的HTML内容将符合预期:
<html> <body> <div>Hello world! | value1 | value2</div> </body> </html>
原参考代码
原XSLT代码(xslt2.xsl)
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" indent="yes"/> <xsl:param name="my_param1" /> <xsl:param name="my_param2" /> <xsl:template match="/"> <html> <body> <div> <xsl:value-of select="root/data" /> <xsl:text> | </xsl:text> <xsl:value-of select="$my_param1" /> <xsl:text> | </xsl:text> <xsl:value-of select="$my_param2" /> </div> </body> </html> </xsl:template> </xsl:stylesheet>
原XML代码(input.xml)
<?xml version="1.0" encoding="utf-8"?> <root> <data>Hello world!</data> </root>
内容的提问来源于stack exchange,提问作者Boris Hoeller
相关产品推荐
相关产品推荐

