XML technologies / XML / Python & XML / Querying XML with XPath / Compiling XPath expressions

(Excerpt from "Python & XML" by Christopher A. Jones & Fred L. Drake, Jr.)

In this section, we use the function Evaluate from the 4XPath API to apply XPath expressions to a node-set. The 4XPath API is already available for using XPath programmatically in Python and offers considerable capabilities.

Most of the XPath API focuses on supporting XPath expressions, since XPath is a standard. However, 4XPath provides several optimizations for programmers who want to embed XPath processing in their applications.

The functions Compile and Context help developers create compiled XPath expressions for repeated use on multiple documents. For example, if you receive many XML documents from customers or suppliers, you may want to apply an XPath expression to each as it arrives, to determine what to do with it or where to route it within your organization. Applying already compiled XPath expressions to each document makes your application faster because the expressions no longer need to be parsed.

The function Compile returns an expression object with a method named evaluate, similar to the function Evaluate used earlier in this section. However, the method expects a Context object rather than a node. Compiling the expression and then using the compiled version is relatively simple:

expression = Compile("ship/@name")
context = Context(dom.documentElement)
nodes = expression.evaluate(context)

The first step is to create an expression; the second is to create the context for the document or node-set you are working with. Execute the expression by calling the evaluate method on the compiled expression object, as shown in the following example.

Example: xp-2.py

#!/usr/local/bin/python

import sys

from xml.dom.ext.reader import PyExpat
from xml.xpath import Compile
from xml.xpath.Context import Context

reader = PyExpat.Reader( )
dom = reader.fromStream(sys.stdin)

expression = Compile("ship/@name")
context = Context(dom.documentElement)
nodes = expression.evaluate(context)

print "Knoten: ", nodes

When run from the command line with ships.xml as input, the program produces the following output:

$ python xp-2.py < ships.xml
Knoten: [<Attribute Node at a1cd9c: Name="name", Value="USS Enterprise">,
<Attribute Node at a2305c: Name="name", Value="USS Voyager">,
<Attribute Node at a2b7fc: Name="name", Value="USS Enterprise">,
<Attribute Node at a33fdc: Name="name", Value="USS Enterprise">,
<Attribute Node at a3a30c: Name="name", Value="USS Sao Paulo">]

Your Python and XML toolkit is now almost complete. In Transforming XML with XSLT we explore another core technology. We then discuss integrating XML into existing systems and building new systems with Python and XML.

  

 

 

 

back to top