Last active
January 27, 2023 10:51
-
-
Save revolunet/1154906 to your computer and use it in GitHub Desktop.
XML/XSLT with Python/lxml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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 |
Thanks a lot! You forgot an f in the name of the function xsl_transormation. ;-)
Will this supports XSLT2.0
lxml only supports XSLT 1.0
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
Will this supports XSLT2.0