6

[Python] Use XSL to Transform XML (XSLT)

 3 years ago
source link: https://siongui.github.io/2012/09/27/python-xslt-xml/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Python] Use XSL to Transform XML (XSLT)

Updated: February 18, 2015

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

#!/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:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK