[Python] Use XSL to Transform XML (XSLT)


To transform XML document into another XML document (XSLT) in Python, we use lxml library (library for processing XML and HTML in the Python language.) to do the transformation for us.

First, we need a XML document, which is to be transformed, and a XSL document, which instructs how to do the transformation. The following sample Python script demonstrates how to do XSLT:

xslt.py | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# -*- coding:utf-8 -*-

from lxml import etree

def transform(xmlPath, xslPath):
  # read xsl file
  xslRoot = etree.fromstring(open(xslPath).read())

  transform = etree.XSLT(xslRoot)

  # read xml
  xmlRoot = etree.fromstring(open(xmlPath).read())

  # transform xml with xslt
  transRoot = transform(xmlRoot)

  # return transformation result
  return etree.tostring(transRoot)

if __name__ == '__main__':
  print(transform('./s0101m.mul0.xml', './tipitaka-latn.xsl'))

In the last line, the path of XML and XSL files are passed as arguments to the transform function, which returns the content (strings) of transformed XML document. To know the details of XSLT in lxml library, please see reference [1]. If you would like to know how to perform XSLT using JavaScript, please see reference [2].


References:

[1]XPath and XSLT with lxml
[2]XSLT - On the Client