XPath from a Python application
The SaxonC Python interface is custom-designed API for XPath processing, allowing integrated access to all Saxon's XML processing capabilities in a uniform way. The Python API is directly built upon the C++ API for XPath.
You can evaluate an XPath expression using the Python interface in a number of ways, for instance as follows:
-
Create a PySaxonProcessor and set any global configuration options on the
PySaxonProcessor
. -
Build the source document by calling
new_document_builder()
to create aDocumentBuilder
, setting appropriate options, and then calling theparse_xml()
method. This returns a PyXdmNode which can be supplied as the context item to the XPath expression. -
Call
new_xpath_processor()
to create a PyXPathProcessor, and set any options required for the specific XPath execution (for example, declaring namespace prefixes that are used in the XPath expression, the initial context node, and the values of any variables referenced in the expression). -
To compile and evaluate the expression, call one of the methods
evaluate()
,evaluate_single()
oreffective_boolean_value()
to execute a specified XPath expression. -
The result of an XPath expression is in general a PyXdmValue, representing a value as defined in the XDM data model (that is, a sequence of nodes and/or atomic values). Subclasses of
XdmValue
include PyXdmItem, PyXdmNode, and PyXdmAtomicValue, and these relate directly to the corresponding concepts in XDM. Various methods are available to translate between this model and native Python data types.
Note that the PyXPathProcessor
only provides compile-and-go methods to execute an
expression directly without going through an explicit compilation process. This provides a simpler
approach if the expression is only evaluated once; but means that a PyXPathProcessor
is
not really suitable for reuse.
Examples of the use of the Python API to evaluate XPath expressions are included in the
SaxonC download file in the directory pypi
, see file test_saxonc.py
and also the test
driver in testsuite_driver/xslt30_test_suite_driver.py
.