Path: redb-route/redb.Route.XPath2/XPath2Expression.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.XPath2/XPath2Expression.cs
----
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using redb.Route.Abstractions;
using redb.Route.Expressions;
using Engine = Wmhelp.XPath2.XPath2Expression;
using EngineIterator = Wmhelp.XPath2.XPath2NodeIterator;
namespace redb.Route.XPath2;
///
/// An XPath 2.0 expression, usable in every position that takes an .
///
///
///
/// XPath 1.0 has no regular expressions, no sequences, no date arithmetic and no conditional; a
/// route that needs one of those has to leave the language. XPath 2.0 has all of them —
/// matches, replace, tokenize, distinct-values, string-join,
/// avg, max, if…then…else, for $x in … return …,
/// some/every … satisfies, xs:date comparisons, instance of.
///
///
/// What this is not. XQuery. let, where and order by are XQuery
/// clauses, not XPath 2.0 ones, and the engine rejects them — so there is no sorting and no
/// grouping here. Filtering goes in a predicate (for $o in /orders/order[total > 8] return …)
/// rather than in a where. A full XQuery processor is not shipped: every .NET
/// implementation of one is commercial.
///
///
/// The path is compiled once, when the route is built, so a malformed expression fails the build
/// rather than the first message — the same rule the rest of the expression layer follows.
///
///
public class XPath2Expression : Expression, IPredicateExpression
{
private readonly string _xpath;
private readonly ThreadLocal _compiled;
private readonly IXmlNamespaceResolver? _namespaces;
private readonly IExpression? _source;
private readonly IReadOnlyList<(string Name, IExpression Value)>? _parameters;
private readonly bool _trim;
///
/// Compiles an XPath 2.0 expression.
///
/// The XPath 2.0 expression text.
/// Optional prefix bindings for a namespace-qualified document.
/// Thrown when is null.
///
/// Thrown when the expression does not parse, so a route fails at build time.
///
public XPath2Expression(string xpath, IXmlNamespaceResolver? namespaces = null)
: this(xpath, namespaces, null, null, false)
{
}
private XPath2Expression(
string xpath,
IXmlNamespaceResolver? namespaces,
IExpression? source,
IReadOnlyList<(string Name, IExpression Value)>? parameters,
bool trim)
{
_xpath = xpath ?? throw new ArgumentNullException(nameof(xpath));
_namespaces = namespaces;
_source = source;
_parameters = parameters;
_trim = trim;
// Compile once here so a malformed expression fails the route build — this compilation is
// validation, not the one evaluations use.
try
{
Engine.Compile(_xpath, namespaces);
}
catch (Exception ex)
{
throw new ArgumentException($"Invalid XPath 2.0 expression '{xpath}': {ex.Message}", nameof(xpath), ex);
}
// Evaluations get a compiled form per thread. The engine's compiled expression mutates
// shared slots while binding range variables (for / some / every), so one instance
// evaluated from several threads corrupts — an IndexOutOfRangeException on a good day,
// a neighbouring message's binding on a bad one. Its Clone() shares the same slots, so
// isolation has to come from compiling, and per thread is where compiling stays amortised:
// a pool thread pays the ~30% of one evaluation once, not per message.
var path = _xpath;
var resolver = namespaces;
_compiled = new ThreadLocal(() => Engine.Compile(path, resolver));
}
/// The expression text.
public string Path => _xpath;
///
public XPath2Expression From(IExpression source)
{
ArgumentNullException.ThrowIfNull(source);
return new XPath2Expression(_xpath, _namespaces, source, _parameters, _trim);
}
///
/// Builds a namespace resolver from prefix/URI pairs, for the constructor.
///
///
/// There is deliberately no fluent WithNamespaces(...) here, unlike the XPath 1.0
/// expression. XPath 2.0 resolves prefixes when the expression is compiled, and this
/// type compiles in its constructor so a bad path fails the route build rather than the first
/// message. A prefix therefore has to be known before the object exists; a fluent method could
/// only ever run after the constructor had already rejected the path, so it would be a method
/// that cannot work.
///
/// Prefix/URI pairs.
/// A resolver to hand to the constructor.
public static IXmlNamespaceResolver Namespaces(params (string Prefix, string Uri)[] namespaces)
{
ArgumentNullException.ThrowIfNull(namespaces);
var manager = new XmlNamespaceManager(new NameTable());
foreach (var (prefix, uri) in namespaces)
{
ArgumentException.ThrowIfNullOrWhiteSpace(prefix, nameof(namespaces));
ArgumentException.ThrowIfNullOrWhiteSpace(uri, nameof(namespaces));
manager.AddNamespace(prefix, uri);
}
return manager;
}
///
public XPath2Expression Trimmed(bool trim = true)
=> new(_xpath, _namespaces, _source, _parameters, trim);
///
public XPath2Expression WithParameters(params (string Name, IExpression Value)[] parameters)
{
ArgumentNullException.ThrowIfNull(parameters);
foreach (var (name, value) in parameters)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name, nameof(parameters));
ArgumentNullException.ThrowIfNull(value, nameof(parameters));
if (name[0] == '$')
throw new ArgumentException(
$"XPath parameter name '{name}' must be written without the '$': the '$' belongs " +
"in the path, not in the binding.", nameof(parameters));
}
var merged = _parameters is null or { Count: 0 }
? parameters
: [.. _parameters, .. parameters];
return new XPath2Expression(_xpath, _namespaces, _source, merged, _trim);
}
///
public override T Evaluate(IExchange exchange) => XPath2Values.Convert(EvaluateRaw(exchange), _xpath, _trim);
///
public bool Matches(IExchange exchange) => XPath2Values.ToBoolean(EvaluateRaw(exchange));
///
/// Runs the compiled expression and returns the engine's own result: a sequence, a navigator,
/// a string, a number or a boolean.
///
private object? EvaluateRaw(IExchange exchange)
{
var input = _source is null ? exchange.In.getBody