11

I need to process XSLT using python, currently I'm using lxml which only support XSLT 1, now I need to process XSLT 2 is there any way to use saxon XSLT processor with python?

Maliq
  • 145
  • 1
  • 2
  • 9

5 Answers5

17

There are two possible approaches:

  1. set up an HTTP service that accepts tranformation requests and implements them by invoking Saxon from Java; you can then send the transformation requests from Python over HTTP

  2. use the Saxon/C product, currently available on prerelease: details here: http://www.saxonica.com/saxon-c/index.xml

Michael Kay
  • 147,186
  • 10
  • 83
  • 148
  • @Maliqf, which approach did you end up taking? and how was your experience with it – Vijay Kumar Dec 16 '15 at 17:41
  • 3
    I wrap Saxon/C in a thin Boost-Python wrapper. It's not difficult to do providing you know a bit of C/C++ - it's just a bit of boilerplate on-top of the the C++ examples given on Saxon's website. You can use the supplied PHP API as a guide on how to structure your Python API. I did it for exactly the reasons stated, no XSLT 3 support native to Python. It works well for me - specifically it's fast, unlike forking a child saxon process or HTTP requests. – Phil Jul 12 '18 at 12:29
8

A Python interface for Saxon/C is in development and worth a look:

https://github.com/ajelenak/pysaxon

ond1
  • 621
  • 5
  • 8
5

At the moment there is not, but you could use the subprocess module to use the Saxon processor:

import subprocess

subprocess.call(["saxon", "-o:output.xml", "-s:file.xml", "file.xslt"])
Bruno
  • 834
  • 13
  • 17
4

Saxon/C release 1.2.0 is now out with XSLT 3.0 support for Python3 see details:

http://www.saxonica.com/saxon-c/index.xml

ond1
  • 621
  • 5
  • 8
  • 1
    By now, this should be promoted to correct answer. Also cf. https://stackoverflow.com/questions/59059768/making-saxon-c-available-in-python for a step-by-step description. – Chiarcos Mar 14 '22 at 12:48
  • SaxonC 11 has since been released. – ond1 Mar 15 '22 at 10:04
1

If you're using Windows:

Download the zip file Saxon-HE 9.9 for Java from http://saxon.sourceforge.net/#F9.9HE and unzip the file to C:\saxon

Use this Python code:

import os
import subprocess

def file_path(relative_path):
    folder = os.path.dirname(os.path.abspath(__file__))
    path_parts = relative_path.split("/")
    new_path = os.path.join(folder, *path_parts)
    return new_path

def transform(xml_file, xsl_file, output_file):
    """all args take relative paths from Python script"""
    input = file_path(xml_file)
    output = file_path(output_file)
    xslt = file_path(xsl_file)

    subprocess.call(f"java -cp C:\saxon\saxon9he.jar net.sf.saxon.Transform -t -s:{input} -xsl:{xslt} -o:{output}")
Webucator
  • 1,960
  • 18
  • 28