Skip to content

Instantly share code, notes, and snippets.

@revolunet
Last active January 27, 2023 10:51
Show Gist options
  • Select an option

  • Save revolunet/1154906 to your computer and use it in GitHub Desktop.

Select an option

Save revolunet/1154906 to your computer and use it in GitHub Desktop.
XML/XSLT with Python/lxml
#!/usr/bin/python
# transform any XML with a XSLT
# you can pass additional parameters for your stylesheet
def xsl_transformation(xslfile, xmlfile = None, xmlstring = None, params={}):
from lxml import etree
import StringIO
xslt_tree = etree.XML(utils.readfile(xslfile))
transform = etree.XSLT(xslt_tree)
xml_contents = xmlstring
if not xml_contents:
if xmlfile:
xml_contents = utils.readfile(xmlfile)
else:
xml_contents = '<?xml version="1.0"?>\n<foo>A</foo>\n'
f = StringIO.StringIO(xml_contents)
doc = etree.parse(f)
f.close()
transform = etree.XSLT(xslt_tree)
result = transform(doc, **params)
return result
@michaelfreiberg
Copy link

Thanks a lot! You forgot an f in the name of the function xsl_transormation. ;-)

@michaelfreiberg
Copy link

michaelfreiberg commented May 26, 2022

Will this supports XSLT2.0

lxml only supports XSLT 1.0

@kishvanchee
Copy link

Is there an alternative to using lxml? I have a usecase where I cannot install lxml as part of the package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment