'Example for setting (multiple) parameters in Python LXML XSLT
Looked for the solution to this problem for a while since the documentation isn't really clear on it.
I ended up using the method below, and thought I'd share back.
Solution 1:[1]
Apparently you can chain parameter arguments when applying the XSLT to the original xml tree. I found the most reliable way is to always use the tree.XSLT.strparam() method for wrapping the argument values. Not really needed I guess for simpler types like string or integers. But this method works regardless.
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" omit-xml-declaration="no"/>
<xsl:param name="var1"/>
<xsl:param name="var2"/>
<!-- actual sheet omitted because example -->
</xsl:stylesheet>
from lxml import etree
var = "variable string"
original_tree = etree.parse("original.xml")
xslt_tree = etree.parse("transform.xsl")
xslt = etree.XSLT(xslt_tree)
lom_tree = xslt(original_tree, var1=etree.XSLT.strparam("str_example"), var2=etree.XSLT.strparam(var))
print(etree.tostring(lom_tree, pretty_print=True))
Solution 2:[2]
Actually the concern about using strparam is only that when you don't read carefully enough the xlst documentation of lxml, you don't realize that anything you pass as just a string is interpreted as a xpath !
transform = etree.XSLT(xslt_tree)
doc_root = etree.XML('<a><b>Text</b></a>')
### "5" is a numeric value, so it's sent as is
result = transform(doc_root, a="5")
### "/a/b/text()" *and* "test" are both interpreted as a xpath !
result = transform(doc_root, a="/a/b/text()")
result = transform(doc_root, a="test")
### to actually send the string "test", you *must* quote it twice or use strparam
result = transform(doc_root, a="'test'")
result = transform(doc_root, a=etree.XSLT.strparam("test")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | jmd |
