Path: redb-route/redb.Route/Expressions/XPathExpression.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/Expressions/XPathExpression.cs
----
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Predicates;
namespace redb.Route.Expressions;
///
/// Expression for evaluating XPath queries against the message body in an .
///
///
/// Extracts data from an XML document using W3C XPath 1.0 expressions.
/// Supports , , string XML, and POCO bodies
/// (auto-serialized to XML). Optionally accepts an
/// for querying namespace-qualified documents.
///
public class XPathExpression : Expression, IPredicateExpression
{
private readonly string _xpath;
private readonly string _effectivePath;
private readonly IXmlNamespaceResolver? _namespaceResolver;
private readonly XPathResult _result;
private readonly IExpression? _source;
private readonly bool _trim;
private readonly IReadOnlyList<(string Name, IExpression Value)>? _parameters;
///
/// Initializes a new instance of the class.
///
/// The XPath expression used to extract data.
///
/// Optional namespace resolver for querying documents with XML namespaces.
///
///
/// The XPath-level type of the result. The default, , is
/// XPath's own default.
///
///
/// What to run the path against. null — the default — means the message body.
///
/// Trim whitespace off extracted text. Default false.
/// Thrown when is null.
public XPathExpression(
string xpath,
IXmlNamespaceResolver? namespaceResolver = null,
XPathResult result = XPathResult.NodeSet,
IExpression? source = null,
bool trim = false)
: this(xpath, namespaceResolver, result, source, trim, null)
{
}
private XPathExpression(
string xpath,
IXmlNamespaceResolver? namespaceResolver,
XPathResult result,
IExpression? source,
bool trim,
IReadOnlyList<(string Name, IExpression Value)>? parameters)
{
_xpath = xpath ?? throw new ArgumentNullException(nameof(xpath));
_namespaceResolver = namespaceResolver;
_result = result;
_source = source;
_trim = trim;
_parameters = parameters;
// string(), number() and boolean() are XPath's own coercions, so asking the engine for
// them is both shorter and more faithful than converting the node-set ourselves.
_effectivePath = result switch
{
XPathResult.String => $"string({_xpath})",
XPathResult.Number => $"number({_xpath})",
XPathResult.Boolean => $"boolean({_xpath})",
_ => _xpath
};
}
///
/// Initializes a new instance of the class with an explicit
/// XPath-level result type.
///
/// The XPath expression used to extract data.
/// The XPath-level type of the result.
public XPathExpression(string xpath, XPathResult result)
: this(xpath, null, result)
{
}
///
/// Returns the same expression reading instead of the message body.
///
///
/// XPath("/invoice/id").From(Header("original-request")). Without it, parsing XML that
/// arrived in a header means moving it into the body first — an extra step that also damages
/// the body for the rest of the route.
///
/// The expression producing the XML to read.
/// A new expression; this one is unchanged.
public XPathExpression From(IExpression source)
{
ArgumentNullException.ThrowIfNull(source);
return new XPathExpression(_xpath, _namespaceResolver, _result, source, _trim, _parameters);
}
///
/// Returns the same expression with prefixes bound to namespace URIs, so a path can address a
/// namespace-qualified document.
///
///
///
/// XPath("/s:Envelope/s:Body").WithNamespaces(("s", "http://schemas.xmlsoap.org/soap/envelope/")).
/// The expression has always accepted an , but only through
/// its constructor — a route written in the DSL had no way to reach it, which made every
/// namespaced document unqueryable from a route without dropping out of the DSL.
///
///
/// The prefixes are the expression's own: they need not match the ones in the document, only
/// the URIs must. Camel keeps namespace sets in a registry and refers to them by name
/// (namespacesRef) because its XML DSL cannot write a map inline; in C# the map is
/// ordinary code, so a shared set is an ordinary variable.
///
///
/// Prefix/URI pairs.
/// A new expression; this one is unchanged.
public XPathExpression WithNamespaces(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 new XPathExpression(_xpath, manager, _result, _source, _trim, _parameters);
}
///
/// Returns the same expression with whitespace trimmed off the text it extracts.
///
///
/// Off by default, which is where this library has always been and differs from Camel's
/// trim=true. For a single value XPath answers this itself —
/// XPath("normalize-space(/order/name)") — but a node-set of several values cannot be
/// normalised from inside XPath 1.0, and an indented document gives every one of them the
/// surrounding whitespace.
///
/// Whether to trim; the parameter exists so the option can be turned back off.
/// A new expression; this one is unchanged.
public XPathExpression Trimmed(bool trim = true)
=> new(_xpath, _namespaceResolver, _result, _source, trim, _parameters);
///
/// Returns the same expression with named XPath variables bound to expressions, so a value from
/// the message can take part in the query without being pasted into its text.
///
///
///
/// XPath("/order[@id=$id]").WithParameters(("id", Header("orderId"))). The value is
/// passed to the engine as a value: it is compared, never parsed, so a header holding
/// B-2' or '1'='1 selects an order with that literal id and matches nothing, rather than
/// changing what the query asks.
///
///
/// The alternative is building the path by concatenation, which Camel offers as
/// allowSimple — and which is the reason XPath injection has a CodeQL query and an OWASP
/// entry of its own. Binding values instead is old and settled practice: JAXP's
/// XPathVariableResolver, XQuery's declare variable $x external, .NET's
/// XsltArgumentList, and prepared statements in SQL are all the same idea.
///
///
/// The path also stays one constant string whatever the data, which is what lets a compiled
/// expression be reused; concatenation defeats that by construction.
///
///
/// XPath only. jpath has no equivalent, and not because of the library: RFC 9535 has no
/// variables at all, so there is nothing for JsonPath.Net to expose.
///
///
/// Variable names (without the $) and the expressions producing their values.
/// A new expression; this one is unchanged.
public XPathExpression 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 XPathExpression(_xpath, _namespaceResolver, _result, _source, _trim, merged);
}
///
/// Parameters are evaluated against a message, so an evaluation that has no message cannot
/// honour them — and silently dropping a binding would turn a query into a different query.
///
private IExchange RequireExchange(IExchange? exchange)
=> exchange ?? throw new InvalidOperationException(
$"XPath '{_xpath}' has bound parameters, which need an exchange to evaluate against. " +
"The two-argument xpath() function of the expression language does not carry them; " +
"use the expression object form.");
///
///
/// Thrown when the exchange body is null or the XPath expression cannot be evaluated.
///
public override T Evaluate(IExchange exchange) => ConvertResult(EvaluateRaw(exchange));
///
/// Evaluates the expression in a condition position.
///
///
///
/// A node-set answers whether the path matched: XPath 1.0 reads a node-set as true exactly
/// when it is non-empty, and the content of the matched nodes never enters the question. So
/// Filter(XPath("/order/discount")) passes a message whose discount is 0, and an
/// empty <vip/> counts as a match.
///
///
/// A scalar — from string(...), count(...) > 0, or an explicit
/// — is a value like any other and goes through the single DSL
/// truthiness rule, so "0" is false there. To read a node's content as a
/// boolean instead, ask for the CLR type: XPath<bool>("/order/flag").
///
///
/// The exchange to test.
/// true when the expression holds for the exchange.
public bool Matches(IExchange exchange)
{
var raw = EvaluateRaw(exchange);
return raw is IEnumerable