2

I have a xslt script which run on single xml files,I need to come out with a code of python so that i can run this xslt using that code and insert some things in those output of xslt by using some python code?Is it possible to call a external xslt script using python?

For eg

input dir have some xmls ,xslt runs on these input xml and create files in output directory using python script.

Navin Dalal
  • 181
  • 3
  • 10

2 Answers2

1

Yes, this is possible, see How to transform XML with XSLT using Python, or the documentation.

With regards to using multiple XML files, you have several options:

  1. Use a parameter and set its value to the document URIs you want to load and use the document function in XSLT to load multiple input documents
  2. If you just know the location and it is a directory, some processors allow you to use `document('dir/with/xml/*.xml)'
  3. If that fails, you can create a URIResolver. How to do that depends on the processor you use.

With regard to your question on creating multiple output documents, this is less easy with XSLT 1.0 (which is typically used with Python), but you can switch to using XSLT 2.0 with Python, though this requires a bit more effort to set up. Once you have this going, you can use xsl:result-document to create multiple result documents to dynamically calculated locations, if you so prefer.

Community
  • 1
  • 1
Abel
  • 56,041
  • 24
  • 146
  • 247
0

You can do it using lxml, but it only support xslt 1

import os
import lxml.etree as ET

inputpath = "D:\\temp\\"
xsltfile = "D:\\temp\\test.xsl"
outpath = "D:\\output"


for dirpath, dirnames, filenames in os.walk(inputpath):
            for filename in filenames:
                if filename.endswith(('.xml', '.txt')):
                    dom = ET.parse(inputpath + filename)
                    xslt = ET.parse(xsltfile)
                    transform = ET.XSLT(xslt)
                    newdom = transform(dom)
                    infile = unicode((ET.tostring(newdom, pretty_print=True)))
                    outfile = open(outpath + "\\" + filename, 'a')
                    outfile.write(infile)

to use xslt 2 you can check options from Use saxon with python

Maliq
  • 315
  • 1
  • 3
  • 11