Bundle: redb-route / redb.Route.XPath2 (redb.Route.XPath2.txt), 5 files Snapshot: 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 Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt ==== Path: redb-route/redb.Route.XPath2/README.md 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/README.md ---- # redb.Route.XPath2 > Documentation and articles: XPath 2.0 expressions for redb.Route, usable in every position that takes an expression. ```csharp using static redb.Route.XPath2.XPath2Dsl; From("direct:orders") .Filter(XPath2("some $o in /orders/order satisfies number($o/total) > 100")) .SetHeader("ids", XPath2("string-join(/orders/order[number(total) > 100]/@id, ',')")) .To("direct:large-orders") .EndFilter(); ``` ## What it adds over the built-in XPath 1.0 XPath 1.0 has no regular expressions, no sequences, no date arithmetic and no conditional, so a route that needs one of those has to leave the language. XPath 2.0 has them: | | | |---|---| | regular expressions | `matches`, `replace`, `tokenize` | | sequences | `distinct-values`, `reverse`, `index-of`, `empty`, `string-join` | | aggregates | `avg`, `max`, `min` | | conditional | `if (…) then … else …` | | iteration | `for $o in /orders/order return …` | | quantifiers | `some $o in … satisfies …`, `every $o in … satisfies …` | | types and dates | `xs:date('2020-01-01')`, `instance of`, `treat as`, value comparisons `eq` / `gt` | | strings | `upper-case`, `lower-case`, `substring-after`, `substring-before` | ## What it is not **This is XPath 2.0, not XQuery.** `let`, `where` and `order by` are XQuery clauses and the engine rejects them — when the route is built, not on the first message. So there is **no sorting** and **no grouping** here. Filtering goes in a predicate rather than in a `where`: ```csharp XPath2("for $o in /orders/order[number(total) > 8] return string($o/@id)") // yes XPath2("for $o in /orders/order where number($o/total) > 8 return $o") // rejected: XQuery ``` A full XQuery processor is not shipped because every .NET implementation of one is commercial. If you have a licence for one, the XSLT engine seam (`IXsltEngineFactory`) is the place to plug it in for transformation; see `docs/V4/12-XQUERY.md`. There is also no `xpath2()` function in the `${…}` expression language: that language lives in the core assembly, which does not know this package exists. Use the expression object. ## The rest of the surface Everything the XPath 1.0 expression grew is here too, with one deliberate difference. ```csharp XPath2("/invoice/id").From(Header("original-request")) // read something other than the body XPath2("/orders/order[@id=$id]").WithParameters(("id", Header("orderId"))) // bound, never concatenated XPath2("/order/name").Trimmed() // trim extracted text XPath2("/s:Envelope/s:Body", ("s", "http://schemas.xmlsoap.org/soap/envelope/")) // namespaces ``` Namespaces are given at construction rather than through a fluent `WithNamespaces(...)`, because XPath 2.0 resolves prefixes while **compiling**, and this expression compiles as soon as it exists so that a bad path fails the route build. A fluent method could only run after the constructor had already rejected the path. Bound parameters are compared, never parsed: a header holding `B-2' or '1'='1` selects an order with that literal id and matches nothing. ## A namespace trap If your own code lives in a namespace under `redb.Route`, the simple name `XPath2` resolves to this package's namespace and shadows the imported factory. Spell it `XPath2Dsl.XPath2(…)` there. Code in any other namespace is unaffected. ## Licence and dependencies The package is Apache-2.0, like the rest of redb.Route. It depends on [XPath2.Net](https://github.com/StefH/XPath2.Net) (`XPath2`, **MS-PL**), which has no dependencies of its own — so the whole graph is two assemblies. `XPath2.Extensions` is deliberately **not** referenced: it is MIT but pulls in Newtonsoft.Json, which this framework removed on purpose, and it adds only non-official extras. MS-PL is a permissive, OSI-approved licence: it allows commercial and closed-source use and grants patent rights. It is not GPL-compatible, which matters only if you intend to combine it with GPL-licensed code. XPath2.Net reports conformance of 12954 of 15133 XQTS 1.0.2 cases (85.6%). Path: redb-route/redb.Route.XPath2/XPath2Dsl.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/XPath2Dsl.cs ---- using System.Xml; using redb.Route.Abstractions; namespace redb.Route.XPath2; /// /// Factory methods for XPath 2.0 expressions, written to be imported: /// using static redb.Route.XPath2.XPath2Dsl; /// /// /// /// The XPath 1.0 helpers live on RouteBuilder as protected members, which a package outside /// the core assembly cannot extend. A static import gives the same shape at the call site — /// .Filter(XPath2("some $o in /orders/order satisfies $o/total > 100")) — without the core /// having to know this package exists. /// /// public static class XPath2Dsl { /// Creates an XPath 2.0 expression over the message body. /// The XPath 2.0 expression text. public static XPath2Expression XPath2(string path) => new(path); /// Creates an XPath 2.0 expression with namespace prefixes bound. /// The XPath 2.0 expression text. /// Prefix/URI pairs. /// /// The prefixes go in here rather than into a fluent call, because XPath 2.0 resolves them /// while compiling and the expression compiles as soon as it exists — see /// . /// public static XPath2Expression XPath2(string path, params (string Prefix, string Uri)[] namespaces) => new(path, XPath2Expression.Namespaces(namespaces)); /// Creates an XPath 2.0 expression with an explicit namespace resolver. /// The XPath 2.0 expression text. /// The resolver to use. public static XPath2Expression XPath2(string path, IXmlNamespaceResolver namespaces) => new(path, namespaces); /// Creates an XPath 2.0 expression whose result is converted to . /// The XPath 2.0 expression text. public static TypedXPath2Expression XPath2(string path) => new(path); /// /// Java-style alias, matching the xpath(...) spelling of the 1.0 helpers. public static XPath2Expression xpath2(string path) => new(path); /// /// Java-style alias. public static TypedXPath2Expression xpath2(string path) => new(path); } /// /// An XPath 2.0 expression that remembers the CLR type its result should take, so a pipeline /// asking for Evaluate<object> still gets that type. /// /// The target CLR type. public sealed class TypedXPath2Expression : redb.Route.Expressions.Expression { private readonly XPath2Expression _inner; /// Creates a typed XPath 2.0 expression. /// The XPath 2.0 expression text. public TypedXPath2Expression(string path) : this(new XPath2Expression(path)) { } private TypedXPath2Expression(XPath2Expression inner) => _inner = inner; /// public TypedXPath2Expression From(IExpression source) => new(_inner.From(source)); /// public TypedXPath2Expression Trimmed(bool trim = true) => new(_inner.Trimmed(trim)); /// public TypedXPath2Expression WithParameters(params (string Name, IExpression Value)[] parameters) => new(_inner.WithParameters(parameters)); /// public override T Evaluate(IExchange exchange) { if (typeof(T) == typeof(object)) return (T)(object)_inner.Evaluate(exchange)!; return _inner.Evaluate(exchange); } /// public override void SetValue(IExchange exchange, object value) => _inner.SetValue(exchange, value); } 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() : _source.Evaluate(exchange); if (input is null) throw new InvalidOperationException(_source is null ? "Exchange body is null. Cannot evaluate XPath 2.0 expression." : "The source expression produced no value, so there is nothing for the XPath 2.0 expression to read."); var node = redb.Route.Expressions.XPathExpression.ResolveXNode(input); try { // Evaluate takes the context item and the bindings, both per message; the compiled // form is this thread's own (see the constructor for why). return _compiled.Value!.Evaluate(new NodeContext(node.CreateNavigator()), Bindings(exchange)); } catch (InvalidOperationException) { throw; } catch (Exception ex) { throw new InvalidOperationException($"Error evaluating XPath 2.0 '{_xpath}': {ex.Message}", ex); } } private IDictionary? Bindings(IExchange exchange) { if (_parameters is null or { Count: 0 }) return null; var bindings = new Dictionary(); foreach (var (name, value) in _parameters) bindings[new XmlQualifiedName(name)] = XPath2Values.ToEngineValue(value.Evaluate(exchange)); return bindings; } /// public override void SetValue(IExchange exchange, object value) => throw new NotSupportedException("XPath2Expression does not support setting values."); /// /// /// Always thrown: the expression language has no xpath2() function to serialize into. /// public override string ToTemplateString() => throw new NotSupportedException( "XPath2Expression has no template form: the expression language has no xpath2() function. " + "Use the expression object where a route takes an IExpression."); /// The context item an evaluation runs against — one node, at position one of one. private sealed class NodeContext(XPathNavigator navigator) : Wmhelp.XPath2.IContextProvider { public XPathItem Context => navigator; public int CurrentPosition => 1; public int LastPosition => 1; } } Path: redb-route/redb.Route.XPath2/XPath2Values.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/XPath2Values.cs ---- using System.Globalization; using System.Xml.Linq; using System.Xml.XPath; using redb.Route.Predicates; using EngineIterator = Wmhelp.XPath2.XPath2NodeIterator; namespace redb.Route.XPath2; /// /// Turns what the XPath 2.0 engine returns into what a route asked for. /// /// /// XPath 2.0 returns a sequence where 1.0 returned a node-set, and a sequence can hold atomic /// values as well as nodes — tokenize('a,b', ',') yields two strings that were never in the /// document. The conversions below therefore work on items rather than on nodes, but land on the /// same shapes the XPath 1.0 expression produces, so a route can move between the two languages /// without its surrounding code changing. /// internal static class XPath2Values { /// /// Reads a result in a condition position. /// /// /// A sequence answers whether anything matched, exactly as a node-set does in XPath 1.0. A /// single atomic value is a value like any other and goes through the one DSL truthiness rule, /// so "0" is false there — which is the rule this framework applies everywhere, and is /// deliberately not XPath 2.0's effective-boolean-value table, whose answer for a lone /// "0" string is true. /// internal static bool ToBoolean(object? raw) { if (raw is not EngineIterator iterator) return RouteTruthiness.ToBoolean(raw); var items = Drain(iterator); return items.Count switch { 0 => false, 1 when items[0] is not XObject => RouteTruthiness.ToBoolean(items[0]), _ => true }; } /// Converts a result to the requested CLR type. internal static T Convert(object? raw, string path, bool trim) { if (raw is not EngineIterator iterator) return ConvertScalar(raw, path, trim); var items = Drain(iterator); if (items.Count == 0) { if (typeof(T).IsValueType && Nullable.GetUnderlyingType(typeof(T)) is null) throw new InvalidOperationException( $"No values found for XPath 2.0 expression '{path}' (expected non-nullable {typeof(T).Name})."); return default!; } return items.Count == 1 ? ConvertSingle(items[0], path, trim) : ConvertMany(items, path, trim); } /// /// Converts a CLR value into something the engine will bind to a $name variable. /// /// /// Formatting is invariant for the same reason it is everywhere else here: a decimal separator /// taken from the server's locale would make one route match different documents on different /// machines. /// internal static object ToEngineValue(object? value) => value switch { null => string.Empty, bool or string or int or long or double or DateTime => value, decimal m => (double)m, float f => (double)f, sbyte or byte or short or ushort or uint or ulong => System.Convert.ToInt64(value, CultureInfo.InvariantCulture), IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), _ => value.ToString() ?? string.Empty }; // ── Items ── /// /// Reads a sequence into ordinary CLR objects: LINQ-to-XML nodes stay nodes, atomic values /// become their typed values. /// private static List Drain(EngineIterator iterator) { var items = new List(); foreach (XPathItem item in iterator) { if (item is XPathNavigator navigator && navigator.UnderlyingObject is XObject node) items.Add(node); else if (item.IsNode) items.Add(item.Value); else items.Add(item.TypedValue); } return items; } private static string Text(object? item, bool trim) { var text = item switch { null => string.Empty, XElement e => e.Value, XAttribute a => a.Value, XText t => t.Value, XComment c => c.Value, XProcessingInstruction pi => pi.Data, XDocument d => d.Root?.Value ?? string.Empty, // The engine can hand back a bare navigator (result type Navigator) rather than an // iterator; its Value is the node's string value, which is what text means here. XPathItem xpathItem => xpathItem.Value, string s => s, IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture), _ => item.ToString() ?? string.Empty }; return trim ? text.Trim() : text; } // ── Conversions ── private static T ConvertScalar(object? value, string path, bool trim) { if (value is T direct) return direct; if (typeof(T) == typeof(string)) return (T)(object)Text(value, trim); if (typeof(T) == typeof(object)) return (T)(object)(value is string s ? (trim ? s.Trim() : s) : value)!; return Parse(Text(value, trim), path); } private static T ConvertSingle(object? item, string path, bool trim) { if (typeof(T) == typeof(object)) return (T)(object)(item is XObject ? SmartParse(Text(item, trim)) : item)!; if (item is T direct) return direct; if (typeof(T) == typeof(string)) return (T)(object)Text(item, trim); return Parse(Text(item, trim), path); } private static T ConvertMany(List items, string path, bool trim) { var texts = items.Select(item => Text(item, trim)).ToArray(); if (typeof(T) == typeof(string)) return (T)(object)string.Join(", ", texts); if (typeof(T) == typeof(string[]) || typeof(T) == typeof(object)) return (T)(object)texts; if (typeof(T) == typeof(int[])) return (T)(object)texts.Select(v => int.Parse(v, CultureInfo.InvariantCulture)).ToArray(); if (typeof(T) == typeof(double[])) return (T)(object)texts.Select(v => double.Parse(v, CultureInfo.InvariantCulture)).ToArray(); if (typeof(T) == typeof(XElement[])) return (T)(object)items.OfType().ToArray(); if (typeof(T) == typeof(List)) return (T)(object)items.OfType().ToList(); if (typeof(T).IsArray) { var elementType = typeof(T).GetElementType()!; var array = Array.CreateInstance(elementType, texts.Length); for (var i = 0; i < texts.Length; i++) array.SetValue(System.Convert.ChangeType(texts[i], elementType, CultureInfo.InvariantCulture), i); return (T)(object)array; } throw new InvalidOperationException( $"Cannot convert {items.Count} results of XPath 2.0 '{path}' to {typeof(T).Name}."); } private static object SmartParse(string text) { if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var i)) return i; if (double.TryParse(text, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out var d)) return d; if (bool.TryParse(text, out var b)) return b; return text; } private static T Parse(string text, string path) { var target = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); if (target == typeof(bool)) { if (bool.TryParse(text, out var b)) return (T)(object)b; if (text == "1") return (T)(object)true; if (text == "0") return (T)(object)false; } try { return (T)System.Convert.ChangeType(text, target, CultureInfo.InvariantCulture); } catch (Exception ex) when (ex is InvalidCastException or FormatException or OverflowException) { throw new InvalidOperationException( $"Cannot convert the result '{text}' of XPath 2.0 '{path}' to {typeof(T).Name}.", ex); } } } Path: redb-route/redb.Route.XPath2/redb.Route.XPath2.csproj 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/redb.Route.XPath2.csproj ---- redb.Route.XPath2 XPath 2.0 expressions for redb.Route: regular-expression, sequence, date and type functions that XPath 1.0 does not have, usable in every position that takes an expression. Built on XPath2.Net (MS-PL), with no transitive dependencies. esb;routing;xpath;xpath2;xml README.md