Programmatically apply an XSL transform outside the browser
I have XML data which I want to be able to display in a browser through an XSL Transform, and also compile with XeLaTeX. Inside the XML file, I have set the stylesheet to be the one for the browser, and currently, to get LaTeX output I 开发者_StackOverflow社区have to go into the XML file, change that, open it in a browser, copy it into a file, save the file and run XeLaTeX against it.
Instead, I would like to leave the XML file associated with the XSLT stylesheet that transforms it to XHTML, and just have a build script that would:
- Apply the LaTeX XSL transform file to the XML file, writing the result to a
.tex
file. - Run XeLaTeX against it.
- Run XeLaTex against it again (the document requires second-pass).
- Clean up log files, etc., unless instructed not to do so.
I know how to do #2-#4. What is the best way to accomplish #1? For example, is there a Python3 recipe for applying an XSL transform to an XML document?
If your stylesheet written in the XSLT 1.0 you can use libxslt through lxml (libxml2 & libxslt python bindings). Look for lxml examples (link to google web cache, because actual page aren't available on the http://lxml.de)
Following the lead given by @Phillip Kovalev, I have come up with this Python3 code:
from lxml import etree
def transform(xsltpath:str, xmlpath:str):
return etree.XSLT(etree.parse(xsltpath))(etree.parse(xmlpath))
def main():
import sys
print(transform(sys.argv[1], sys.argv[2]))
if __name__ == '__main__':
main()
Kudos to the developer of lxml
--works like a charm!
精彩评论