Compiling XPath Expressions

In this chapter, we use the Evaluate function from the 4XPath API to apply XPath expressions against node sets. For programmatic use of XPath within Python, the 4XPath API is readily available and offers considerable power.

Most of the XPath API is geared towards supporting XPath expressions, as XPath is a standard. But for the programmer embedding XPath processing functionality into their applications, there is some optimization found in 4XPath.

The Compile and Context functions aid the developer to create compiled XPath expressions for repeated use against multiple documents. For example, if you are accepting large numbers of XML documents from customers or suppliers, you may want to apply an XPath expression to each one (as it arrives) to figure out what to do with it, or where to route it within your organization. Having your XPath expression readily compiled and applied against each unique document adds speed to your application, as you’ve done away with the need to parse the XPath expression.

The Compile function returns an expression object that supports an evaluate method similar to the Evaluate function used thus far in this chapter. However, the method expects a Context object, not a node. The task of compiling an expression, and then using the compiled version, is fairly simple:

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

The first step is to generate an expression; the second ...

Get Python & XML now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.