使用SaxOne和Python使用XSLT转换JSON

2024-05-28 21:09:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个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的技术


Tags: 文件csvjsonresulteeinitialjarfile
1条回答
网友
1楼 · 发布于 2024-05-28 21:09:19

我认为您希望使用call_template...而不是应用模板,例如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

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

相关问题 更多 >

    热门问题