Path: redb-route/redb.Route.JsonTransform/JsonTransformXmlContribution.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.JsonTransform/JsonTransformXmlContribution.cs
----
using System.Xml.Linq;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Xml;
namespace redb.Route.JsonTransform;
///
/// The <transformJson> element: JSONata
/// over the body, the specification either referenced by a locator (a path or
/// assembly:Name/path) or inline as the element's content (CDATA welcome) — exactly one
/// of the two.
///
public sealed class JsonTransformXmlContribution : IXmlElementContribution
{
///
public string Name => "transformJson";
///
public XmlElementKind Kind => XmlElementKind.Step;
///
public ElementSpec Spec => new(Name, Kind,
[
new AttributeSpec("spec", AttributeType.String) { Resource = true },
// The format spells the values lowercase (string/node); parsing is case-insensitive.
new AttributeSpec("output", AttributeType.Enum, EnumValues: ["string", "node"]),
],
[], AllowsTextContent: true);
///
public IRouteDefinition Apply(XElement element, IRouteDefinition current, XmlParseContext context)
{
var locator = context.Attr(element, "spec");
var inline = Text(element);
if ((locator is null) == (inline is null))
{
context.AddError(element, " takes either the spec locator or inline JSONata content, not both.");
return current;
}
var output = JsonTransformOutput.String;
if (context.Attr(element, "output") is { } outputName && !Enum.TryParse(outputName, ignoreCase: true, out output))
{
context.AddError(element, $"'{outputName}' is not a transform output ({string.Join(", ", Enum.GetNames())}).");
return current;
}
return locator is not null
? current.TransformJson(locator, output)
: current.TransformJson(TextSource.Inline(inline!), output);
}
///
public void Print(XElement element, XmlCodeWriter code)
{
var output = element.Attribute("output")?.Value is { } o
? $"JsonTransformOutput.{Enum.Parse(o, true)}"
: null;
var source = element.Attribute("spec")?.Value is { } locator
? XmlCodeWriter.Str(locator)
: $"TextSource.Inline({XmlCodeWriter.Str(Text(element) ?? "")})";
code.Verb(element, "TransformJson", output is null ? [source] : [source, output]);
}
private static string? Text(XElement element)
{
var text = string.Concat(element.Nodes().OfType().Select(t => t.Value));
return string.IsNullOrWhiteSpace(text) ? null : text.Trim();
}
}