微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 SaxonEE 和 Python 使用 XSLT 转换 JSON

如何解决使用 SaxonEE 和 Python 使用 XSLT 转换 JSON

我正在尝试编写一个 Python 脚本,使用 XSLT 将 JSON 转换为文本文件 (CSV)。

使用 saxon-ee-10.5.jar,我可以通过运行以下命令(Windows 10)成功执行所需的转换:

java -cp saxon-ee-10.5.jar com.saxonica.Transform -it -xsl:styling.xslt -o:result.csv

如何使用 Python 实现相同的结果?我一直在尝试使用 Saxon-EE/C,但我不确定我想要发生的事情是否可能。

这是我迄今为止尝试过的示例。我的 XSLT 已经为 initial.json 文件定义了一个 $in 参数,但是 PyXslt30Processor.apply_templates_returning_file() 似乎需要调用 PyXslt30Processor.set_initial_match_selection(),我不确定如果可以传递非 XML 文件

from saxonc import PySaxonProcessor
with PySaxonProcessor(license=True) as proc:
  xslt30proc = proc.new_xslt30_processor()
  xslt30proc.set_initial_match_selection(file_name='initial.json')
  content = xslt30proc.apply_templates_returning_file(
    stylesheet_file='styling.xslt',output_file='result.csv'
  )
  print(content)

我想用 Saxon-EE/C 完成什么,还是应该尝试从 Python 调用 Java 的技术?

解决方法

我认为您想使用 call_template... 而不是 apply-templates,例如https://www.saxonica.com/saxon-c/doc/html/saxonc.html#PyXslt30Processor-call_template_returning_file

xslt30proc.call_template_returning_file(None,stylesheet_file='styling.xslt',output_file='result.csv'
  )

使用 None 作为模板名称应该与在命令行上使用 -it 相同,即首先调用名为 xsl:initial-template 的模板。

在这种情况下不要使用 xslt30proc.set_initial_match_selection

不过,在 xslt30proc.set_cwd('.') 调用之前设置 call_template_returning_file 可能会有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。