XML technologies / XML / Python & XML / Getting started with Python and XML / The power of Python and XML
(Excerpt from “Python & XML” by Christopher A. Jones & Fred L. Drake, Jr.)
Having introduced the XML world, let us see what Python contributes. We will examine Python features relevant to XML and present specific examples. As a decidedly high-level language, Python includes powerful data structures in its core and libraries. Newer versions, from 2.0 onward, offer particularly good Unicode support and an impressive variety of encodings, along with an excellent, fast XML parser exposing XML character data as Unicode strings. The standard library also implements the industry-standard interfaces DOM and SAX for working with XML data; additional support for alternative parsers and interfaces is also available.
Of course, much the same could be said of other modern high-level languages. Java certainly has an impressive library of useful data structures, and Perl offers comparable structures. Why choose Python over these languages and libraries? Several features matter; here are the most important:
Python source is easy to read and maintain.
The interactive interpreter makes testing code fragments easy.
Python is remarkably portable without restricting access to platform-specific features.
Its object-oriented features are powerful without being obscure.
Many languages can do what Python does, but few combine all its incidental qualities. These do not necessarily make it more powerful, but easier to use, reducing programming hours. You gain time to find better solutions to real problems or move on to the next one. Let us explore these features in detail.
Easy to read and maintain
Python offers remarkable clarity of expression. Programmers from other languages may be surprised by significant whitespace, but everyone seems to find Python source more readable than languages requiring special characters to mark code structure. Python’s structures are not simpler; the different syntax merely makes its source look much cleaner.
Whitespace also avoids minor stylistic differences such as brace placement, increasing visual consistency across programmers’ code. Though this may seem minor, maintaining someone else’s code becomes much easier because you can focus on its actual structure and algorithms. For an individual it is a pleasant side effect; for a company it lowers maintenance costs.
Exploratory programming in an interactive interpreter
Many modern high-level languages provide an interpreter, but few as successfully as Python. Others, such as Java, generally offer none. Looking at Perl, rightly regarded as powerful on the command line, we find no rich interactive interpreter. Starting Perl without a script simply waits for a complete script on the console and executes it when finished. Commands can be supplied on the command line, but individual statements cannot be run and their results inspected step by step to verify each fragment. Python’s interactive interpreter offers a rich environment for executing individual statements and testing their results.
Portability without restrictions
Python’s interpreter is among the most portable available. It runs on diverse platforms, from PDAs and embedded systems to some of the most powerful multiprocessors ever built, and probably on more operating systems than any other interpreter. Carefully written applications inherit much of this portability. Python offers abstractions sufficient to hide platform differences while letting programmers use platform-specific services when needed.
If an application needs facilities or libraries Python does not provide, extensions are easy to add. Extension modules, usually written in C or C++ though other languages are possible, give Python efficient access to external facilities.
Powerful but accessible object orientation
Once, object-oriented programming (OOP) was said to solve most technical programming problems. Programmers knew better, stepped back and turned the concepts into useful tools to apply when appropriate, though how and when remains debatable. Unfortunately, many strongly object-oriented languages are cumbersome, like C++ and to a lesser extent Java, or not widely accepted as general-purpose languages, like Eiffel.
Python differs. It supports objects without much of the syntactic overhead of widespread object-oriented languages, making new types easy to define. It is highly polymorphic, with interfaces defined far less rigidly than in C++ or Java. Useful objects need not contain code that exists only to satisfy an interface and is never actually used. Combined with the standard library’s wide range of interfaces, this reveals reusable objects’ value while preserving ease of implementing useful interfaces.
Python tools for XML
Python’s XML tools mainly come from three packages, listed from most widely used to largest:
The Python standard library
PyXML, produced by the Python XML Special Interest Group
4Suite from Fourthought, Inc.
The standard library provides a minimal but useful set of XML interfaces, including the popular Expat parser, the lightweight Simple API for XML (SAX), and a simple core implementation of the Document Object Model (DOM). The DOM implementation supports Level 1 and much of Level 2 of the W3C specification but few optional features. Standard-library material originated in PyXML, with further contributions from leading Python XML developers.
PyXML provides substantially more functionality. It adds parsers, a more extensive DOM including optional features, adapters giving other parsers SAX support, parsing and evaluation of XPath expressions, XSLT transformations, and many utilities. Many active Python XML programmers maintain it collaboratively.
4Suite is not a superset of the other packages but should supplement PyXML. It includes task-specific DOM implementations, support for the XLink and XPointer specifications, and tools for Resource Description Framework data (RDF).
These are the packages used throughout the book. Installing Python and XML tools explains how to obtain and install them. Other packages exist; see Additional Python XML tools for brief descriptions and further online information.
The SAX and DOM APIs
SAX and DOM are the two most basic and widely used XML APIs. They differ fundamentally, so choosing the right one for your application matters.
SAX defines a relatively primitive interface easily supported by parsers, but demands detailed knowledge of XML information processing and operations from application programmers. Its advantage is low overhead: no large data structures are built until the application needs them. Many operations can therefore be faster and larger documents processed efficiently. It is event-driven, resembling GUI input-event processing more than manipulating a prebuilt structure. How does a parser produce events, and what are they?
SAX defines handler interfaces applications can implement to receive event notifications. Object methods are called upon encountering corresponding events in XML; each method can represent the event itself, fitting object-oriented parsing. Events are categorized as content, document type, lexical and error events, each with a separate interface. Applications register handlers only for categories of interest. Python provides base classes so you need implement only the methods you need; inherited, unused methods simply do nothing.
Content events are most commonly used; the most important are startElement, characters and endElement. In The Simple API for XML we examine SAX thoroughly. First, let us quickly extract useful document information. We use a simple document to make clear how to build something more complex. Here it is:
<catalog>
<book isbn="1-56592-724-9">
<title>The Cathedral & the Bazaar</title>
<author>Eric S. Raymond</author>
</book>
<book isbn="1-56592-051-1">
<title>Making TeX Work</title>
<author>Norman Walsh</author>
</book>
<!-- Stellen Sie sich hier weitere Einträge vor... -->
</catalog> To create a dictionary mapping ISBN numbers in the attribute isbn of the element book to book titles, the content of the title elements, we create a content handler examining the three events above, as in the following example.
Example: bookhandler.py
import xml.sax.handler
class BookHandler(xml.sax.handler.ContentHandler):
def __init__(self):
self.inTitle = 0
self.mapping = {}
def startElement(self, name, attributes):
if name == "book":
self.buffer = ""
self.isbn = attributes["isbn"]
elif name == "title":
self.inTitle = 1
def characters(self, data):
if self.inTitle:
self.buffer += data
def endElement(self, name):
if name == "title":
self.inTitle = 0
self.mapping[self.isbn] = self.bufferExtracting the information is now trivial. If the preceding code is in bookhandler.py and the sample document in books.xml, an interactive session could do this:
>>> import xml.sax
>>> import bookhandler
>>> import pprint
>>>
>>> parser = xml.sax.make_parser( )
>>> handler = bookhandler.BookHandler( )
>>> parser.setContentHandler(handler)
>>> parser.parse("books.xml")
>>> pprint.pprint(handler.mapping)
{u'1-56592-051-1': u'Making TeX Work',
u'1-56592-724-9': u'The Cathedral & the Bazaar'}For handler method reference material, see The Python SAX API.
DOM is nearly SAX’s opposite. SAX provides a small moving window onto input, leaving the application to infer the whole. DOM gives it the whole document and leaves it to discover details. Instead of reporting events as the parser encounters syntax, an object represents the entire document hierarchically. Though the document need not be fully parsed and held in memory before delivery, most implementations do so for simplicity. Some avoid it: a DOM implementation can parse lazily or keep the parsed document in persistent storage instead of main memory.
DOM provides objects called nodes representing parts of a document to applications. Different node types represent different constructs. DOM nodes do not directly correspond to SAX events, though many are similar. Compare elements and their contents: SAX uses start and end events, with intervening events representing content. DOM provides one element object and methods accessing child nodes representing content. Distinct node types represent elements, text and practically everything else in XML.
We examine more detail and advanced DOM examples in The Document Object Model; a detailed API reference appears in Python DOM API. For a first impression, let us quickly write code doing what bookhandler.py did with SAX, this time using the simple DOM implementation in Python’s standard library, as the following example shows.
Example: dombook.py
import pprint
import xml.dom.minidom
from xml.dom.minidom import Node
doc = xml.dom.minidom.parse("books.xml")
mapping = {}
for node in doc.getElementsByTagName("book"):
isbn = node.getAttribute("isbn")
L = node.getElementsByTagName("title")
for node2 in L:
title = ""
for node3 in node2.childNodes:
if node3.nodeType == Node.TEXT_NODE:
title += node3.data
mapping[isbn] = title
# Abbildung hat nun den gleichen Wert wie im SAX-Beispiel:
pprint.pprint(mapping)This is clearly something quite different! Though the DOM example uses about as much code, reusable components can be hard to develop, whereas SAX experience often suggests them with little refactoring. DOM code can be reused, but requires a different mindset. In return, DOM lets you manipulate any part of a fully known document, and different application components can extract content in different ways without reparsing. For some applications, that justifies DOM over SAX.
Other ways to extract information
SAX and DOM are powerful XML tools but require much code and attention to detail for effective large applications. Complex data demands substantial work merely to extract interesting document portions. What tools normally help with complex data? Higher abstractions, such as more capable APIs and task-specific languages, and preprocessing, transforming data into a form better suited to the task. Fortunately, both are available for Python XML work.
To specify part of a document using potentially complex criteria, an XML user employs a language expressing that specification concisely and precisely: XML Path Language, or XPath for short. 4Suite supports XPath, and support was recently added to PyXML. XPath selects DOM-tree nodes by element names, attribute values, text and node relationships. Querying XML with XPath covers XPath details, including using it with a DOM tree in Python.
You may instead want a new document with less information or a different arrangement. We need a way to specify a transformation producing another document. That is provided by XML Stylesheet Language Transformations (XSLT). Originally part of a new stylesheet specification, XSLT is an XML-based transformation language. Its output is most often XML or HTML. Transforming XML with XSLT describes the language and its use in Python.
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