Transforming an XML Document Using XSLT
Credit: David Ascher
Problem
You have an XSLT transform that you wish to programmatically run through XML documents.
Solution
The solution depends on the XSLT processor you’re using. If you’re using Microsoft’s XSLT engine (part of its XML Core Services package), you can drive the XSLT engine through its COM interface:
def process_with_msxslt(xsltfname, xmlfname, targetfname):
import win32com.client.dynamic
xslt = win32com.client.dynamic.Dispatch("Msxml2.DOMDocument.4.0")
xslt.async = 0
xslt.load(xsltfname)
xml = win32com.client.dynamic.Dispatch("Msxml2.DOMDocument.4.0")
xml.async = 0
xml.load(xmlfname)
output = xml.transformNode(xslt)
open(targetfname, 'wb').write(output)If you’d rather use Xalan’s XSLT engine, it’s as simple as using the right module:
import Pyana
output = Pyana.transform2String(source=open(xmlfname).read( ),
style=open(xsltfname).read( ))
open(targetfname, 'wb').write(output)Discussion
There are many different ways that XML documents need to be processed. Extensible Stylesheet Language Transformations (XSLT) is a language that was developed specifically for transforming XML documents. Using XSLT, you define a stylesheet, which is a set of templates and rules that defines how to transform specific parts of an XML document into arbitrary outputs.
The XSLT specification is a World Wide Web Consortium Recommendation (http://www.w3.org/TR/xslt) that has been implemented by many different organizations. The two most commonly used ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access