Evaluating XPath Expressions using s9api
The s9api interface is a custom-designed API for Saxon, allowing integrated access to all Saxon's XML processing capabilities in a uniform way, taking advantage of the type safety offered by generics in Java 5.
You can evaluate an XPath expression using the s9api interface in a number of ways, for instance as follows:
-
Create a
Processor
and set any global configuration options on theProcessor
. -
Build the source document by calling
newDocumentBuilder()
to create a document builder, setting appropriate options, and then calling thebuild()
method. This returns anXdmNode
which can be supplied as the context item to the XPath expression. -
Call
newXPathCompiler()
to create anXPathCompiler
, and set any options that are local to a specific compilation (notably declaring namespace prefixes that are used in the XPath expression). -
Call the
compile()
method to compile an expression. The result is anXPathExecutable
, which can be used as often as you like in the same thread or in different threads. -
To evaluate the expression, call the
load()
method on theXPathExecutable
. This creates anXPathSelector
. TheXPathSelector
can be serially reused, but it must not be shared across multiple threads. Set any options required for the specific XPath execution (for example, the initial context node, the values of any variables referenced in the expression), and then call one of the methodsiterator()
evaluate()
, orevaluateSingle()
to execute the XPath expression. -
Because the
XPathSelector
is anIterable
, it is possible to iterate over the results directly using the Java 5 "for-each" construct. -
The result of an XPath expression is in general an
XdmValue
, representing a value as defined in the XDM data model (that is, a sequence of nodes and/or atomic values). Subclasses ofXdmValue
includeXdmItem
,XdmNode
, andXdmAtomicValue
, and these relate directly to the corresponding concepts in XDM. Various methods are available to translate between this model and native Java data types.
The XdmCompiler
also has
compile-and-go methods evaluate()
and evaluateSingle()
to execute
an expression directly without going through an explicit compilation process. This provides
a simpler approach if the expression is only evaluated once. The XdmCompiler
also has the option of caching compiled expressions, so that if the same expression is
evaluated repeatedly, the compiled form of the expression is re-used.
Examples of the use of s9api to evaluate XPath expressions are included in the
saxon-resources
file, see module S9APIExamples.java
.