Evaluating XPath Expressions from C#

The Saxon.Api interface is a custom-designed API for Saxon, allowing integrated access to all Saxon's XML processing capabilities in a uniform way.

You can evaluate an XPath expression using the Saxon.Api interface in a number of ways, for instance as follows:

  1. Create a Processor and set any global configuration options on the Processor.

  2. Build the source document by calling NewDocumentBuilder() to create a document builder, setting appropriate options, and then calling one of the various Build() methods. This returns an XdmNode which can be supplied as the context item to the XPath expression.

  3. Call NewXPathCompiler() to create an XPathCompiler, and set any options that are local to a specific compilation (notably declaring namespace prefixes that are used in the XPath expression).

  4. Call the Compile() method to compile an expression. The result is an XPathExecutable, which can be used as often as you like in the same thread or in different threads.

  5. To evaluate the expression, call the Load() method on the XPathExecutable. This creates an XPathSelector. The XPathSelector 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 methods GetEnumerator(), Evaluate(), or EvaluateSingle() to execute the XPath expression.

  6. Because the XPathSelector is an IEnumerable, it is possible to iterate over the results directly using the C# "foreach" construct.

  7. 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 of XdmValue include XdmItem, XdmNode, and XdmAtomicValue, and these relate directly to the corresponding concepts in XDM. Various methods are available to translate between this model and native C# data types.

Examples of the use of Saxon.Api to evaluate XPath expressions are included in the saxon-resources file, see module Examples.cs.