XSL transformations in Python

I want to describe how to do XSL transformations in Python by using 4Suite. It is a really easy, and requires just a few steps:

  1. Install 4Suite technologies for Python:
    $ sudo yum install python-4Suite-XML
  2. Create a required XML file (for example, simple1.xml):
    <!-- The stylesheet to apply -->
    <?xml-stylesheet href="simple.xsl" type="text/xsl"?>
    <document cache-methods="get,post">
            <title>Simple XSLT sample</title>
                    <heading>Simple XSLT sample</heading>
                            This is a sample text.
  3. Create a required XSL file (for example, simple1.xsl):
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
                    Output an XHTML/transitional document (uses html output method
                    as Xalan does not support xhtml)
            <xsl:output method="html" indent="yes" version="4.0" encoding="us-ascii"
    media-type="text/html" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
    doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" />
            <!-- Match the document root -->
            <xsl:template match="/document">
                    <!-- Output an html document -->
                            <!-- Copy the title -->
                            <head><title><xsl:value-of select="title" /></title></head>
                            <!-- Process the body -->
                                    <xsl:apply-templates select="body" />
            <!-- Match a heading -->
            <xsl:template match="heading">
                    <h1><xsl:apply-templates select="node()" /></h1>
            <!-- Match a paragraph -->
            <xsl:template match="paragraph">
                    <p><xsl:apply-templates select="node()" /></p>
  4. Run Python code:
    $ ipython
    In [1]: from Ft.Xml.Xslt import Transform
    In [2]: result = Transform('simple1.xml', 'simple1.xsl')
    In [3]: print result
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        <meta content="text/html; charset=us-ascii" http-equiv="Content-Type">
        <title>Simple XSLT sample</title>
        <h1>Simple XSLT sample</h1>
                            This is a sample text.

The main magic is Transform function - it takes XML and XSL files and do transformation. For further digging take a look to 4Suite demos.

Happy transformations! :-)


Popular posts from this blog

Trac Ticket Workflow

Introduction to ReviewBoard

Python vs JS vs PHP for embedded systems