XML technologies / XML / Python & XML / Transforming XML with XSLT / Embedding XSLT transformations in Python
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
XML often stores a document’s “core,” while transformations integrate its data into other systems. For example, an order received as XML over the web could be forwarded in several directions and formats. Parse it to populate Oracle tables, transform it to HTML for an internal website, or convert it to another XML vocabulary for suppliers.
Wherever XML goes, runtime XSLT transformation is crucial. 4XSLT works nicely inside Python programs. Here we build an executable Python CGI (Common Gateway Interface) program for Linux and Apache, or any server configured to permit external CGI programs.
Two stylesheets, one XML document and an executable CGI are involved. The first stylesheet displays XML as HTML. The second also adds HTML for editing the XML text in the browser and updating it on the server. The Python script chooses the stylesheet according to your actions and updates the XML source on disk. It must be in a directory where the web user, corresponding to user nobody under Apache and Unix, can write a new XML file.
Creating the XML sources
First create an XML document. Once the CGI exists, later updates can happen in the browser. For now, store this code on disk as story.xml:
<?xml version="1.0"?>
<story>
<title>...</title>
<body>
...
</body>
</story>Be sure to save it as story.xml so the CGI can find it when applying stylesheets.
Creating a simple stylesheet
The first stylesheet displays plain HTML using XSLT’s method apply-templates. A form button labeled Editieren reloads the CGI in editing mode, which uses the second stylesheet to show the edit form. The simple stylesheet follows.
Example: story.xsl
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="story">
<html>
<head><title>Die Story-Seite</title></head>
<body><xsl:apply-templates/></body>
</html>
</xsl:template>
<xsl:template match="title">
<h1><xsl:apply-templates/></h1>
</xsl:template>
<xsl:template match="body">
<p><xsl:apply-templates/></p>
<p>
<form action="xslt.cgi" method="get">
<input type="hidden" name="mode" value="edit"/>
<input type="submit" value="Editieren"/>
</form>
</p>
</xsl:template>
</xsl:stylesheet>The figure shows the transformed XML in a browser.
Figure: Transformation with a simple stylesheet
Creating an editing stylesheet
The second stylesheet is similar, but puts XML content into editable browser form fields. Submitting the form updates the disk file, applies the simple stylesheet again, and returns the result to the browser.
Save the editing stylesheet below as edstory.xsl.
Example: edstory.xsl
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="story">
<html>
<head><title>Die Story-Seite</title></head>
<body>
<form action="xslt.cgi" method="get">
<xsl:apply-templates/>
</form>
</body>
</html>
</xsl:template>
<xsl:template match="title">
<h1><xsl:value-of select="."/></h1>
<p>Neuer Titel: <input type="text" name="title" length="20"/></p>
</xsl:template>
<xsl:template match="body">
<p>Neuer Text:
<textarea rows="10" cols="50" name="body"><xsl:value-of select="."/></textarea>
<input type="hidden" name="mode" value="change"/>
<p><input type="submit" value="Abschicken"/></p>
</p>
</xsl:template>
</xsl:stylesheet>The figure shows the edit form. Clicking the “Abschicken” submit button updates XML on disk and reapplies the simple transformation.
Figure: Editing XML in a browser
Creating the CGI script
The script xslt.cgi ties the stylesheets together and coordinates processing and disk updates. Despite browser editing and display, the application is just one CGI and two XSL sheets. Changing source data also remains stored as XML on disk.
Perform transformations programmatically using the class xml.xslt.processor.Processor, assuming 4XSLT was installed as described. At startup, the CGI imports and instantiates the XSLT processor:
#!/usr/local/bin/python
# xlst.cgi
import cgi
import os
import sys
from xml.xslt.Processor import Processor
# Parse Abfrage-String & instanziiere XSLT-Prozessor
query = cgi.FieldStorage( )
xsltproc = Processor( )Using the processor is simple: two methods select a stylesheet and run a transformation, returning a string:
xsltproc.appendStylesheetUri("story.xsl")
html = xsltproc.runUri("story.xml")The method appendStylesheetUri selects the stylesheet. The method runUri transforms the XML source and returns the result as a string.
No transformation happens until the CGI knows your intent, passed in a query string as part of the server request.
Selecting a mode
After obtaining the QUERY_STRING, the CGI determines whether you selected editing, changing or displaying. Without a mode it complains and exits:
mode = query.getvalue("mode", "")
if not mode:
print "<html><body>"
print "<p>Kein Modus angegeben</p>"
print "</html></body>"
sys.exit(0) For a show command, the processor loads the simple stylesheet and XML, returning HTML to the browser:
if mode[0] == "show":
# Wende einfaches Stylesheet auf XML an
xsltproc.appendStylesheetUri("story.xsl")
html = xsltproc.runUri("story.xml")
print html For an edit command, XML is processed with the editing sheet, adding form markup. This is almost identical to show, except for the stylesheet name.
elif mode[0] == "edit":
# Wende formularbasiertes Stylesheet auf XML an
xsltproc.appendStylesheetUri("edstory.xsl")
html = xsltproc.runUri("story.xml")
print html Clicking “Abschicken” after editing submits the result with a change command. The script updates the disk file, transforms it again, and returns the result to the browser.
elif mode[0] == "change":
# Ändere XML-Quelldatei, wiederhole Stylesheet und zeige an
newXML = '<?xml version="1.0"?>\n'
newXML += "\t<story>\n\t<title>"
newXML += query.getvalue("title")[0] + "</title>\n"
newXML += "\t<body>\n"
newXML += query.getvalue("body")[0] + "\n\t</body>\n</story>\n"
fd = open("story.xml", "w")
fd.write(newXML)
fd.close( )
# Führe aktualisiertes XML mit einfachem Stylesheet aus
xsltproc.appendStylesheetUri("story.xsl")
html = xsltproc.runUri("story.xml")
print htmlWithout write permission under the web user, the script fails.
The complete listing follows: xslt.cgi.
Example: xslt.cgi
#!/usr/local/bin/python
# xlst.cgi
import cgi
import os
import sys
from xml.xslt.Processor import Processor
# Parse Abfrage-String & instanziiere xslt-Prozessor
query = cgi.FieldStorage( )
xsltproc = Processor( )
print "Content-type: text/html\r\n"
mode = query.getvalue("mode", "")
if not mode:
print "<html><body>"
print "<p>Kein Modus angegeben</p>"
print "</html></body>"
sys.exit( )
if mode[0] == "show":
# Führe XML mit einfachem Stylesheet aus
xsltproc.appendStylesheetUri("story.xsl")
html = xsltproc.runUri("story.xml")
print html
elif mode[0] == "change":
# Ändere XML-Quelldatei, wiederhole Stylesheet und zeige an
newXML = '<?xml version="1.0"?>\n'
newXML += "\t<story>\n\t<title>"
newXML += query.getvalue("title")[0] + "</title>\n"
newXML += "\t<body>\n"
newXML += query.getvalue("body")[0] + "\n\t</body>\n</story>\n"
fd = open("story.xml", "w")
fd.write(newXML)
fd.close( )
# Führe aktualisiertes XML mit einfachem Stylesheet aus
xsltproc.appendStylesheetUri("story.xsl")
html = xsltproc.runUri("story.xml")
print html
elif mode[0] == "edit":
# Führe XML mit formularbasiertem Stylesheet aus
xsltproc.appendStylesheetUri("edstory.xsl")
html = xsltproc.runUri("story.xml")
print html
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Python & XML” is subject to the same conditions as the bound edition: the work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de