Bundle: redb-route / redb.Route.DataFormats.XmlJson (redb.Route.DataFormats.XmlJson.txt), 12 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.DataFormats.XmlJson/Internal/ArrayPaths.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.DataFormats.XmlJson/Internal/ArrayPaths.cs ---- namespace redb.Route.DataFormats.XmlJson.Internal; /// /// The paths, parsed once: /a/b/c matches the element path from the root, /// //b/c matches its end at any depth. A step without a prefix compares with the local name, a step with one /// compares with the name as the document writes it. /// internal sealed class ArrayPaths { private readonly List<(bool Anywhere, string[] Steps)> _paths = []; public ArrayPaths(IEnumerable paths) { foreach (var path in paths) _paths.Add(Parse(path)); } /// Whether no path is given. public bool IsEmpty => _paths.Count == 0; private static (bool, string[]) Parse(string path) { var anywhere = path.StartsWith("//", StringComparison.Ordinal); if (!anywhere && !path.StartsWith('/')) throw new ArgumentException( $"xmljson arrays path '{path}' starts with '/' (from the root) or '//' (at any depth).", nameof(path)); var steps = path[(anywhere ? 2 : 1)..].Split('/'); if (steps.Any(s => s.Length == 0 || s.Any(char.IsWhiteSpace))) throw new ArgumentException( $"xmljson arrays path '{path}' has an empty or blank step; write it as /Order/Items/Item or //Item.", nameof(path)); return (anywhere, steps); } /// /// Whether the element at the end of (local and written names, root first) is an array. /// public bool Matches(IReadOnlyList<(string Local, string Written)> path) { foreach (var (anywhere, steps) in _paths) { if (steps.Length > path.Count || (!anywhere && steps.Length != path.Count)) continue; var offset = path.Count - steps.Length; var all = true; for (var i = 0; i < steps.Length && all; i++) { var (local, written) = path[offset + i]; all = steps[i].Contains(':') ? string.Equals(steps[i], written, StringComparison.Ordinal) : string.Equals(steps[i], local, StringComparison.Ordinal); } if (all) return true; } return false; } } Path: redb-route/redb.Route.DataFormats.XmlJson/Internal/JsonToXml.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.DataFormats.XmlJson/Internal/JsonToXml.cs ---- using redb.Route.Validation; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; namespace redb.Route.DataFormats.XmlJson.Internal; /// /// JSON to XML in the Json.NET notation, the reverse of . A key is an element; a key under the /// attribute prefix is an attribute (@xmlns and @xmlns:p declare namespaces); the text key is the /// element's text; an array is the element repeated; null is xsi:nil="true". Numbers and booleans are /// written as the JSON writes them. A key that is not an XML name, or a value XML cannot hold where it stands, is an /// error naming its path: nothing is renamed or dropped silently. /// internal sealed class JsonToXml { private static readonly JsonDocumentOptions Reading = new() { MaxDepth = 256 }; private readonly XmlJsonOptions _options; private readonly SchemaModel? _schema; /// The converter of , by its schema when it names one. public JsonToXml(XmlJsonOptions options) : this(options, options.SchemaSet ?? (options.Schema is { } path ? SchemaResolver.Load("xmljson", path, options.SchemaRoot) : null)) { } private JsonToXml(XmlJsonOptions options, XmlSchemaSet? set) { _options = options; _schema = set is null ? null : new SchemaModel(set); } /// The converter without a schema, for content the schema says nothing about (xs:any). internal static JsonToXml Plain(XmlJsonOptions options) => new(options, (XmlSchemaSet?)null); /// Parses and returns the XML document. public XDocument Convert(byte[] json) { JsonNode? node; try { node = JsonNode.Parse(json, documentOptions: Reading); } catch (JsonException ex) { throw new InvalidOperationException($"xmljson: the body is not JSON ({ex.Message}).", ex); } return Convert(node); } /// The XML document of . public XDocument Convert(JsonNode? node) { if (_schema is not null) return new JsonToXmlBySchema(_options, _schema).Convert(node); var scope = new Scope(null); XElement root; if (_options.Root is { } rootName) { if (node is JsonArray) throw new InvalidOperationException( $"xmljson: the JSON is an array, and its items have no element name; wrap it in an object that names them, {{\"Item\": [...]}}, under root={rootName}."); root = Element(rootName, node, scope, "/" + rootName); } else { if (node is not JsonObject top || top.Count != 1) throw new InvalidOperationException( $"xmljson: the JSON is {Describe(node)}; XML has one root element: give the JSON one top-level key, or name the root with root=."); var (name, value) = top.First(); if (value is JsonArray) throw new InvalidOperationException( $"xmljson: the top-level key '{name}' holds an array; XML has one root element: name the root with root=."); root = Element(name, value, scope, "/" + name); } return new XDocument(new XDeclaration("1.0", "utf-8", null), root); } /// The XML text of , UTF-8 without a byte order mark. public byte[] Write(XDocument document) { var settings = new XmlWriterSettings { Encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), Indent = _options.Indent, }; using var stream = new MemoryStream(); using (var writer = XmlWriter.Create(stream, settings)) document.Save(writer); return stream.ToArray(); } private XElement Element(string key, JsonNode? value, Scope parentScope, string path) { // Declarations come first: the element's own name may use a prefix it declares. var scope = new Scope(parentScope); var declarations = new List(); if (value is JsonObject declaring) foreach (var (name, declared) in declaring) if (TryDeclaration(name, out var prefix)) { var uri = Scalar(declared, path + "/" + name) ?? ""; scope.Declare(prefix, uri); declarations.Add(prefix.Length == 0 ? new XAttribute("xmlns", uri) : new XAttribute(XNamespace.Xmlns + prefix, uri)); } var element = new XElement(Name(key, scope, path, element: true), declarations); switch (value) { case null: if (scope.TryResolve("xsi") is null) { scope.Declare("xsi", XmlToJson.Xsi.NamespaceName); element.Add(new XAttribute(XNamespace.Xmlns + "xsi", XmlToJson.Xsi.NamespaceName)); } element.Add(new XAttribute(XmlToJson.Xsi + "nil", "true")); break; case JsonObject members: Members(element, members, scope, path); break; case JsonArray: throw new InvalidOperationException( $"xmljson: {path} is an array inside an array; XML repeats an element, it cannot nest a list in a list."); default: element.Value = Scalar(value, path)!; break; } return element; } private void Members(XElement element, JsonObject members, Scope scope, string path) { foreach (var (name, value) in members) { var at = path + "/" + name; if (TryDeclaration(name, out _)) continue; if (name == _options.TextKey) { element.Add(new XText(Scalar(value, at) ?? "")); continue; } if (name.StartsWith(_options.AttributePrefix, StringComparison.Ordinal) && _options.AttributePrefix.Length > 0) { var attributeName = name[_options.AttributePrefix.Length..]; if (value is null) continue; // an attribute cannot be nil: a null attribute is absent element.Add(new XAttribute(Name(attributeName, scope, at, element: false), Scalar(value, at)!)); continue; } if (value is JsonArray items) { var (itemName, wrapper) = PluralItems(name, element, scope, at); foreach (var item in items) wrapper.Add(Element(itemName, item, scope, at)); continue; } element.Add(Element(name, value, scope, at)); } } /// /// Where the items of the array under go: repeated elements in /// , or, under the plural rule, singular elements in a wrapper /// ("Incidents": [...] gives <Incidents><Incident/>...</Incidents>). /// private (string ItemName, XElement Container) PluralItems(string name, XElement parent, Scope scope, string path) { if (_options.Plural && Plural.SingularFor(LocalPart(name)) is { } singular) { var wrapper = new XElement(Name(name, scope, path, element: true)); parent.Add(wrapper); var prefix = name.Contains(':') ? name[..name.IndexOf(':')] + ":" : ""; return (prefix + singular, wrapper); } return (name, parent); } private static string LocalPart(string name) => name.Contains(':') ? name[(name.IndexOf(':') + 1)..] : name; private bool TryDeclaration(string key, out string prefix) { prefix = ""; if (_options.AttributePrefix.Length == 0 || !key.StartsWith(_options.AttributePrefix, StringComparison.Ordinal)) return false; var rest = key[_options.AttributePrefix.Length..]; if (rest == "xmlns") return true; if (!rest.StartsWith("xmlns:", StringComparison.Ordinal)) return false; prefix = rest["xmlns:".Length..]; return true; } private XName Name(string key, Scope scope, string path, bool element) { var colon = key.IndexOf(':'); var local = colon < 0 ? key : key[(colon + 1)..]; if (!IsName(local) || (colon >= 0 && !IsName(key[..colon]))) throw new InvalidOperationException($"xmljson: {path}: '{key}' is not an XML name."); if (colon < 0) return element && _options.Namespaces == XmlJsonNamespaces.Keep ? scope.Resolve("", path) + local : local; var prefix = key[..colon]; if (prefix == "xsi") return scope.TryResolve(prefix) is { } declared ? declared + local : XmlToJson.Xsi + local; return scope.Resolve(prefix, path) + local; } internal static bool IsName(string name) { try { XmlConvert.VerifyNCName(name); return true; } catch (XmlException) { return false; } } /// The text of a JSON value XML can hold: a string as is, a number or boolean as JSON writes it. internal static string? Scalar(JsonNode? value, string path) => value switch { null => null, JsonValue scalar when scalar.TryGetValue(out var text) => text, JsonValue scalar => scalar.ToJsonString(), _ => throw new InvalidOperationException( $"xmljson: {path} holds {Describe(value)}, where XML has text: an attribute, a text key or a namespace."), }; internal static string Describe(JsonNode? node) => node switch { null => "null", JsonObject o => $"an object of {o.Count} key(s)", JsonArray => "an array", _ => "a value", }; /// The namespace prefixes declared by @xmlns keys, nested as the elements are. private sealed class Scope(Scope? parent) { private readonly Dictionary _prefixes = new(StringComparer.Ordinal); public void Declare(string prefix, string uri) => _prefixes[prefix] = uri; public XNamespace? TryResolve(string prefix) { for (var scope = this; scope is not null; scope = scope.Parent) if (scope._prefixes.TryGetValue(prefix, out var ns)) return ns; return null; } public XNamespace Resolve(string prefix, string path) { if (TryResolve(prefix) is { } ns) return ns; if (prefix.Length == 0) return XNamespace.None; throw new InvalidOperationException( $"xmljson: {path}: the prefix '{prefix}' is not declared; declare it with an \"@xmlns:{prefix}\" key on this element or an enclosing one."); } private Scope? Parent => parent; } } Path: redb-route/redb.Route.DataFormats.XmlJson/Internal/JsonToXmlBySchema.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.DataFormats.XmlJson/Internal/JsonToXmlBySchema.cs ---- using System.Globalization; using System.Text.Json.Nodes; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; namespace redb.Route.DataFormats.XmlJson.Internal; /// /// JSON to XML by a schema. The schema decides what JSON keys alone cannot: the namespace of every element and /// attribute, the order of children (the order the content declares, whatever the order of the keys), which branch of /// a choice is taken, and the text of a value (numbers in the lexical form of their type). A JSON key matches an /// element or attribute by its local name; a prefix on the key only picks the prefix written for that namespace. /// Strict: a key the content has no place for, two branches of one choice, an array where one element is allowed, or /// null where the element is not nillable, is an error naming the JSON path. Whether every required element is present /// is left to validateXsd, the recommended next step. /// internal sealed class JsonToXmlBySchema { private readonly XmlJsonOptions _options; private readonly SchemaModel _schema; private readonly Dictionary _declared = new(StringComparer.Ordinal); // namespace -> prefix from @xmlns keys public JsonToXmlBySchema(XmlJsonOptions options, SchemaModel schema) { _options = options; _schema = schema; } public XDocument Convert(JsonNode? node) { string key; JsonNode? content; if (_options.Root is { } rootName) { key = rootName; content = node; } else { if (node is not JsonObject top || top.Count != 1) throw new InvalidOperationException( $"xmljson: the JSON is {JsonToXml.Describe(node)}; XML has one root element: give the JSON one top-level key, or name the root with root=."); (key, content) = top.First(); } var globals = _schema.GlobalsNamed(LocalPart(key)); if (globals.Count != 1) throw new InvalidOperationException(globals.Count == 0 ? $"xmljson: the root '{key}' is not a global element of the schema." : $"xmljson: the root '{key}' is a global element in {globals.Count} namespaces; the schema cannot tell which."); var declaration = globals[0]; if (content is JsonArray) throw new InvalidOperationException($"xmljson: /{key} holds an array; XML has one root element."); CollectDeclarations(content); var root = Element(declaration.QualifiedName, declaration, content, "/" + key); DeclareNamespaces(root); return new XDocument(new XDeclaration("1.0", "utf-8", null), root); } private XElement Element(XmlQualifiedName name, XmlSchemaElement declaration, JsonNode? value, string path) { var element = new XElement(XName.Get(name.Name, name.Namespace)); var type = declaration.ElementSchemaType; switch (value) { case null: if (!declaration.IsNillable) throw new InvalidOperationException($"xmljson: {path} is null, and the schema does not declare it nillable."); element.Add(new XAttribute(XmlToJson.Xsi + "nil", "true")); break; case JsonObject members: Members(element, type, members, path); break; case JsonArray: throw new InvalidOperationException( $"xmljson: {path} is an array inside an array; XML repeats an element, it cannot nest a list in a list."); default: if (SchemaModel.IsComplexContent(type) && type is XmlSchemaComplexType { ContentType: not XmlSchemaContentType.Mixed }) throw new InvalidOperationException( $"xmljson: {path} holds {JsonToXml.Describe(value)}, and the schema declares element content: an object is expected."); element.Value = Lexical(value, SchemaModel.TextDatatype(type), path); break; } return element; } private void Members(XElement element, XmlSchemaType? type, JsonObject members, string path) { var slots = _schema.Slots(type); var children = new List<(ContentSlot Slot, int Sequence, XElement Element)>(); var branches = new Dictionary(); var sequence = 0; foreach (var (key, value) in members) { var at = path + "/" + key; if (IsDeclaration(key)) continue; if (key == _options.TextKey) { element.Add(new XText(Lexical(value, SchemaModel.TextDatatype(type), at))); continue; } if (_options.AttributePrefix.Length > 0 && key.StartsWith(_options.AttributePrefix, StringComparison.Ordinal)) { Attribute(element, type, key[_options.AttributePrefix.Length..], value, at); continue; } var local = LocalPart(key); var slot = slots.FirstOrDefault(s => !s.Wildcard && s.Name.Name == local) ?? slots.FirstOrDefault(s => s.Wildcard) ?? throw new InvalidOperationException($"xmljson: {at}: the content of {path} in the schema has no place for '{local}'."); if (slot.Branch is { } branch) { if (branches.TryGetValue(branch.Choice, out var taken) && taken.Branch != branch.Branch) throw new InvalidOperationException( $"xmljson: {path} has both '{taken.Key}' and '{key}', two branches of one choice in the schema."); branches[branch.Choice] = (branch.Branch, key); } foreach (var item in Items(slot, key, value, at)) children.Add((slot, sequence++, item)); } foreach (var (_, _, child) in children.OrderBy(c => c.Slot.Order).ThenBy(c => c.Sequence)) element.Add(child); } private IEnumerable Items(ContentSlot slot, string key, JsonNode? value, string path) { if (slot.Wildcard) { // Under xs:any nothing is known: a global declaration of the name if there is one, else the plain reverse. var global = _schema.GlobalsNamed(LocalPart(key)); if (global.Count == 1) return Repeat(value, path, item => Element(global[0].QualifiedName, global[0], item, path)); var plain = JsonToXml.Plain(_options); return Repeat(value, path, item => plain.Convert(new JsonObject { [key] = item?.DeepClone() }).Root!); } var declaration = slot.Declaration!; if (value is JsonArray array && !slot.Repeats) { if (WrapperItem(declaration) is { } inner) { // A schema wrapper: "Items": [...] where Items holds one repeated element writes Items with its items. var wrapper = new XElement(XName.Get(slot.Name.Name, slot.Name.Namespace)); foreach (var item in array) wrapper.Add(Element(inner.Name, inner.Declaration!, item, path)); return [wrapper]; } if (array.Count > 1) throw new InvalidOperationException( $"xmljson: {path} is an array of {array.Count}, and the schema allows one '{slot.Name.Name}' here."); } return Repeat(value, path, item => Element(slot.Name, declaration, item, path)); } /// The one repeated element a wrapper's content consists of, or null. private ContentSlot? WrapperItem(XmlSchemaElement declaration) { var slots = _schema.Slots(declaration.ElementSchemaType); return slots.Count == 1 && slots[0] is { Wildcard: false, Repeats: true } only && declaration.ElementSchemaType is XmlSchemaComplexType { AttributeUses.Count: 0 } ? only : null; } private static IEnumerable Repeat(JsonNode? value, string path, Func one) => value is JsonArray array ? array.Select(one).ToList() : [one(value)]; private void Attribute(XElement element, XmlSchemaType? type, string name, JsonNode? value, string path) { if (value is null) return; // an attribute cannot be nil: a null attribute is absent var local = LocalPart(name); var prefix = name.Contains(':') ? name[..name.IndexOf(':')] : null; if (prefix == "xsi") { element.Add(new XAttribute(XmlToJson.Xsi + local, JsonToXml.Scalar(value, path)!)); return; } var declared = SchemaModel.AttributeNamed(type, local); if (declared is null && !SchemaModel.HasAnyAttribute(type)) throw new InvalidOperationException($"xmljson: {path}: the schema declares no attribute '{local}' here."); var xname = declared is null ? XName.Get(local) : XName.Get(declared.QualifiedName.Name, declared.QualifiedName.Namespace); element.Add(new XAttribute(xname, Lexical(value, declared?.AttributeSchemaType?.Datatype, path))); } /// /// The text of a value in the lexical form of its type: a string as is, a boolean as true/false, a /// number as the JSON writes it, except that a decimal-family type never takes an exponent (1e3 is written /// 1000). /// private static string Lexical(JsonNode? value, XmlSchemaDatatype? datatype, string path) { var text = JsonToXml.Scalar(value, path) ?? ""; if (value is JsonValue number && number.GetValueKind() == System.Text.Json.JsonValueKind.Number && datatype is { TypeCode: not (XmlTypeCode.Double or XmlTypeCode.Float) } && IsNumeric(datatype.TypeCode) && text.IndexOfAny(['e', 'E']) >= 0) return decimal.Parse(text, NumberStyles.Float, CultureInfo.InvariantCulture).ToString(CultureInfo.InvariantCulture); return text; } private static bool IsNumeric(XmlTypeCode code) => code is XmlTypeCode.Decimal or XmlTypeCode.Integer or XmlTypeCode.NonPositiveInteger or XmlTypeCode.NegativeInteger or XmlTypeCode.Long or XmlTypeCode.Int or XmlTypeCode.Short or XmlTypeCode.Byte or XmlTypeCode.NonNegativeInteger or XmlTypeCode.UnsignedLong or XmlTypeCode.UnsignedInt or XmlTypeCode.UnsignedShort or XmlTypeCode.UnsignedByte or XmlTypeCode.PositiveInteger; private bool IsDeclaration(string key) { var p = _options.AttributePrefix; return p.Length > 0 && (key == p + "xmlns" || key.StartsWith(p + "xmlns:", StringComparison.Ordinal)); } /// The prefixes the JSON declares with @xmlns:p keys anywhere, to write them for those namespaces. private void CollectDeclarations(JsonNode? node) { if (node is JsonObject members) { foreach (var (key, value) in members) { var p = _options.AttributePrefix; if (p.Length > 0 && key.StartsWith(p + "xmlns:", StringComparison.Ordinal) && JsonToXml.Scalar(value, key) is { Length: > 0 } uri) _declared.TryAdd(uri, key[(p.Length + "xmlns:".Length)..]); else CollectDeclarations(value); } } else if (node is JsonArray items) { foreach (var item in items) CollectDeclarations(item); } } /// Declares on the root every namespace the document uses: the JSON's prefix, the configured one, or nsN. private void DeclareNamespaces(XElement root) { var used = root.DescendantsAndSelf() .SelectMany(e => e.Attributes().Where(a => !a.IsNamespaceDeclaration).Select(a => a.Name.Namespace).Prepend(e.Name.Namespace)) .Where(ns => ns != XNamespace.None && ns != XNamespace.Xml) .Distinct() .ToList(); var configured = _options.Prefixes.ToDictionary(p => p.Value, p => p.Key, StringComparer.Ordinal); // A generated nsN never takes a prefix the JSON or the options give to another namespace. var taken = new HashSet(_declared.Values.Concat(configured.Values).Append("xsi"), StringComparer.Ordinal); var next = 0; var declarations = new List(); foreach (var ns in used) { string prefix; if (ns == XmlToJson.Xsi) prefix = "xsi"; else if (_declared.TryGetValue(ns.NamespaceName, out var fromJson)) prefix = fromJson; else if (configured.TryGetValue(ns.NamespaceName, out var fromOptions)) prefix = fromOptions; else while (!taken.Add(prefix = "ns" + next++)) { } declarations.Add(new XAttribute(XNamespace.Xmlns + prefix, ns.NamespaceName)); } root.ReplaceAttributes(declarations.Concat(root.Attributes().ToList())); } private static string LocalPart(string name) => name.Contains(':') ? name[(name.IndexOf(':') + 1)..] : name; } Path: redb-route/redb.Route.DataFormats.XmlJson/Internal/Plural.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.DataFormats.XmlJson/Internal/Plural.cs ---- namespace redb.Route.DataFormats.XmlJson.Internal; /// /// The plural-wrapper rule: a parent named as the English plural of its children's name (Incidents / /// Incident) holds a list. The singular candidates of a plural are the regular forms (-ies to -y, /// -es and -s left out) and a short list of irregular ones; a name with none of them is never a plural. /// Names compare as written, case included. /// internal static class Plural { private static readonly Dictionary Irregular = new(StringComparer.OrdinalIgnoreCase) { ["children"] = "child", ["people"] = "person", ["men"] = "man", ["women"] = "woman", ["indices"] = "index", ["matrices"] = "matrix", ["vertices"] = "vertex", ["analyses"] = "analysis", ["criteria"] = "criterion", ["feet"] = "foot", ["teeth"] = "tooth", ["mice"] = "mouse", }; /// Whether is a plural of . public static bool IsPair(string parent, string child) { if (child.Length == 0) return false; foreach (var singular in Singulars(parent)) if (string.Equals(singular, child, StringComparison.Ordinal)) return true; return false; } /// The singular forms may stand for; none for a name that is not a plural. public static IEnumerable Singulars(string plural) { if (Irregular.TryGetValue(plural, out var irregular)) yield return MatchCase(plural, irregular); if (plural.Length > 3 && plural.EndsWith("ies", StringComparison.Ordinal)) yield return plural[..^3] + "y"; if (plural.Length > 2 && plural.EndsWith("es", StringComparison.Ordinal)) yield return plural[..^2]; if (plural.Length > 1 && plural.EndsWith('s') && !plural.EndsWith("ss", StringComparison.Ordinal)) yield return plural[..^1]; } /// /// The one singular JSON to XML writes for the plural , or null when the name is not /// a plural. Irregular first, then -ies to -y (Categories), -es after ss, us, /// x, z, ch, sh (Addresses, Statuses, Boxes), else -s /// (Cases, Incidents). A choice has to be made where English is ambiguous: Movies gives /// Movy; such a name is written with arrays= and an explicit wrapper instead. /// public static string? SingularFor(string plural) { if (Irregular.TryGetValue(plural, out var irregular)) return MatchCase(plural, irregular); if (plural.Length > 3 && plural.EndsWith("ies", StringComparison.Ordinal)) return plural[..^3] + "y"; foreach (var ending in (string[])["sses", "uses", "xes", "zes", "ches", "shes"]) if (plural.Length > ending.Length && plural.EndsWith(ending, StringComparison.Ordinal)) return plural[..^2]; if (plural.Length > 1 && plural.EndsWith('s') && !plural.EndsWith("ss", StringComparison.Ordinal)) return plural[..^1]; return null; } /// The irregular singular with the first letter cased as the plural's (Children gives Child). private static string MatchCase(string plural, string singular) => char.IsUpper(plural[0]) ? char.ToUpperInvariant(singular[0]) + singular[1..] : singular; } Path: redb-route/redb.Route.DataFormats.XmlJson/Internal/SchemaModel.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.DataFormats.XmlJson/Internal/SchemaModel.cs ---- using System.Globalization; using System.Text.Json.Nodes; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; namespace redb.Route.DataFormats.XmlJson.Internal; /// What the schema says about one element of a document: its declaration and whether it repeats. /// The element's type; null under a wildcard with no global declaration (nothing is known). /// Whether the content of its parent allows it more than once. internal sealed record SchemaElement(XmlSchemaType? Type, bool Repeats); /// One place in the content of a complex type, in declaration order. /// The element's qualified name; empty for a wildcard. /// The element declaration; null for a wildcard. /// Whether the place allows the element more than once. /// Position in the content, for writing children in schema order. /// The single-occurrence choice and the branch the place sits in, if any. /// Whether the place is an xs:any. internal sealed record ContentSlot(XmlQualifiedName Name, XmlSchemaElement? Declaration, bool Repeats, int Order, (int Choice, int Branch)? Branch, bool Wildcard); /// /// The knowledge xmljson takes from a compiled . The compiler has already resolved imports, /// includes, groups, extensions and restrictions; this walks the compiled content particles itself, because the /// repetition of an element ref sits on the particle, not on the global declaration a validating reader /// reports. Lookups are lazy and cached per parent type, so recursive types need nothing special. /// internal sealed class SchemaModel { private readonly XmlSchemaSet _set; private readonly Dictionary> _substitutes = []; private readonly System.Collections.Concurrent.ConcurrentDictionary<(XmlSchemaType Parent, XmlQualifiedName Child), SchemaElement?> _children = new(new ParentChildComparer()); public SchemaModel(XmlSchemaSet set) { if (!set.IsCompiled) set.Compile(); _set = set; foreach (XmlSchemaElement element in set.GlobalElements.Values) { if (element.SubstitutionGroup.IsEmpty) continue; if (!_substitutes.TryGetValue(element.SubstitutionGroup, out var members)) _substitutes[element.SubstitutionGroup] = members = []; members.Add(element); } } private static XmlQualifiedName QName(XName name) => new(name.LocalName, name.NamespaceName); /// The root: a global element, or an error naming the root and the namespace. public SchemaElement Root(XName name) => _set.GlobalElements[QName(name)] is XmlSchemaElement element ? new SchemaElement(element.ElementSchemaType, Repeats: false) : throw new InvalidOperationException( $"xmljson: the root element '{name.LocalName}'{NamespaceText(name)} is not a global element of the schema."); /// The global elements whose local name is , for a JSON key that carries no namespace. public IReadOnlyList GlobalsNamed(string local) => _set.GlobalElements.Values.Cast().Where(e => e.QualifiedName.Name == local).ToList(); /// /// The places of the content of , in the order the content declares them: what JSON to XML /// needs to write children in schema order and to tell the branches of a choice apart. Members of a substitution /// group take the place of their head. /// public IReadOnlyList Slots(XmlSchemaType? type) { var slots = new List(); if (type is not XmlSchemaComplexType complex) return slots; var choices = 0; Walk(complex.ContentTypeParticle, false, null); return slots; void Walk(XmlSchemaParticle? particle, bool repeated, (int Choice, int Branch)? branch) { if (particle is null || particle.MaxOccurs == 0) return; var here = repeated || particle.MaxOccurs > 1; switch (particle) { case XmlSchemaElement element: foreach (var declaration in Members(element)) slots.Add(new ContentSlot(declaration.QualifiedName, declaration, here, slots.Count, branch, Wildcard: false)); break; case XmlSchemaChoice choice when !here: var id = ++choices; var index = 0; foreach (XmlSchemaParticle item in choice.Items) Walk(item, here, (id, index++)); break; case XmlSchemaGroupBase group: foreach (XmlSchemaParticle item in group.Items) Walk(item, here, branch); break; case XmlSchemaGroupRef groupRef: Walk(groupRef.Particle, here, branch); break; case XmlSchemaAny: slots.Add(new ContentSlot(XmlQualifiedName.Empty, null, here, slots.Count, branch, Wildcard: true)); break; } } } private IEnumerable Members(XmlSchemaElement element) { if (!element.IsAbstract) yield return element; if (_substitutes.TryGetValue(element.QualifiedName, out var members)) foreach (var member in members) foreach (var nested in Members(member)) yield return nested; } /// The attribute of whose local name is , or null. public static XmlSchemaAttribute? AttributeNamed(XmlSchemaType? type, string local) => type is XmlSchemaComplexType complex ? complex.AttributeUses.Values.Cast().FirstOrDefault(a => a.QualifiedName.Name == local) : null; /// Whether accepts attributes it does not declare (xs:anyAttribute). public static bool HasAnyAttribute(XmlSchemaType? type) => type is XmlSchemaComplexType { AttributeWildcard: not null }; /// /// The child in the content of . Under a wildcard /// (xs:any) a global declaration of that name is used when there is one, else nothing is known (the type is /// null). null when the parent's content has no place for it. /// public SchemaElement? Child(SchemaElement parent, XName name) { if (parent.Type is not XmlSchemaComplexType complex) return parent.Type is null ? new SchemaElement(null, false) : null; var key = (complex, QName(name)); return _children.GetOrAdd(key, k => Find((XmlSchemaComplexType)k.Parent, k.Child)); } private SchemaElement? Find(XmlSchemaComplexType parent, XmlQualifiedName name) { var matches = 0; var repeats = false; XmlSchemaType? type = null; var wildcard = false; var wildcardRepeats = false; Walk(parent.ContentTypeParticle, false); if (matches > 0) return new SchemaElement(type, repeats || matches > 1); if (!wildcard) return null; return _set.GlobalElements[name] is XmlSchemaElement global ? new SchemaElement(global.ElementSchemaType, wildcardRepeats) : new SchemaElement(null, wildcardRepeats); void Walk(XmlSchemaParticle? particle, bool repeated) { if (particle is null || particle.MaxOccurs == 0) return; var here = repeated || particle.MaxOccurs > 1; switch (particle) { case XmlSchemaElement element: var declaration = Matching(element, name); if (declaration is not null) { matches++; repeats |= here; type ??= declaration.ElementSchemaType; } break; case XmlSchemaGroupBase group: foreach (XmlSchemaParticle item in group.Items) Walk(item, here); break; case XmlSchemaGroupRef groupRef: Walk(groupRef.Particle, here); break; case XmlSchemaAny: wildcard = true; wildcardRepeats |= here; break; } } } /// The declaration stands for under : itself, or a member of its substitution group. private XmlSchemaElement? Matching(XmlSchemaElement element, XmlQualifiedName name) { if (element.QualifiedName == name) return element; if (!_substitutes.TryGetValue(element.QualifiedName, out var members)) return null; foreach (var member in members) if (Matching(member, name) is { } found) return found; return null; } /// Whether holds element content (as opposed to text): its value is an object even when empty. public static bool IsComplexContent(XmlSchemaType? type) => type is XmlSchemaComplexType { ContentType: XmlSchemaContentType.ElementOnly or XmlSchemaContentType.Empty or XmlSchemaContentType.Mixed }; /// The datatype of an element's text: a simple type, or a complex type with simple content. public static XmlSchemaDatatype? TextDatatype(XmlSchemaType? type) => type switch { XmlSchemaSimpleType simple => simple.Datatype, XmlSchemaComplexType { ContentType: XmlSchemaContentType.TextOnly } complex => complex.Datatype, _ => null, }; /// The datatype of the attribute on an element of . public static XmlSchemaDatatype? AttributeDatatype(XmlSchemaType? type, XName name) => type is XmlSchemaComplexType complex && complex.AttributeUses[QName(name)] is XmlSchemaAttribute attribute ? attribute.AttributeSchemaType?.Datatype : null; /// /// The JSON value of under : a number for the numeric types, a /// boolean for xs:boolean, the text for every other type. A text that is not of its type is an error naming /// . /// public static JsonNode? Typed(string text, XmlSchemaDatatype? datatype, string where) { if (datatype is null || datatype.Variety != XmlSchemaDatatypeVariety.Atomic) return JsonValue.Create(text); var trimmed = text.Trim(); switch (datatype.TypeCode) { case XmlTypeCode.Boolean: return trimmed switch { "true" or "1" => JsonValue.Create(true), "false" or "0" => JsonValue.Create(false), _ => throw NotOfType(text, "xs:boolean", where), }; case XmlTypeCode.Double or XmlTypeCode.Float: if (trimmed is "INF" or "-INF" or "NaN") return JsonValue.Create(trimmed); // not a JSON number: kept as the schema writes it return double.TryParse(trimmed, NumberStyles.Float, CultureInfo.InvariantCulture, out var real) ? JsonValue.Create(real) : throw NotOfType(text, datatype.TypeCode == XmlTypeCode.Double ? "xs:double" : "xs:float", where); case XmlTypeCode.Decimal or XmlTypeCode.Integer or XmlTypeCode.NonPositiveInteger or XmlTypeCode.NegativeInteger or XmlTypeCode.Long or XmlTypeCode.Int or XmlTypeCode.Short or XmlTypeCode.Byte or XmlTypeCode.NonNegativeInteger or XmlTypeCode.UnsignedLong or XmlTypeCode.UnsignedInt or XmlTypeCode.UnsignedShort or XmlTypeCode.UnsignedByte or XmlTypeCode.PositiveInteger: return decimal.TryParse(trimmed, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out var number) ? JsonValue.Create(number) : throw NotOfType(text, "xs:" + datatype.TypeCode.ToString().ToLowerInvariant(), where); default: return JsonValue.Create(text); } } private static InvalidOperationException NotOfType(string text, string type, string where) => new($"xmljson: {where} holds '{text}', which is not an {type} as the schema declares."); private static string NamespaceText(XName name) => name.Namespace == XNamespace.None ? " (no namespace)" : $" in namespace '{name.NamespaceName}'"; private sealed class ParentChildComparer : IEqualityComparer<(XmlSchemaType Parent, XmlQualifiedName Child)> { public bool Equals((XmlSchemaType Parent, XmlQualifiedName Child) x, (XmlSchemaType Parent, XmlQualifiedName Child) y) => ReferenceEquals(x.Parent, y.Parent) && x.Child == y.Child; public int GetHashCode((XmlSchemaType Parent, XmlQualifiedName Child) obj) => HashCode.Combine(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(obj.Parent), obj.Child); } } Path: redb-route/redb.Route.DataFormats.XmlJson/Internal/XmlToJson.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.DataFormats.XmlJson/Internal/XmlToJson.cs ---- using redb.Route.Validation; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Unicode; using System.Xml.Linq; using redb.Route.Core; namespace redb.Route.DataFormats.XmlJson.Internal; /// /// XML to JSON in the Json.NET notation. The root element is the one key of the result. An element with neither /// attributes nor child elements is its text ("" when empty, null under xsi:nil="true"); any other /// element is an object: attributes under the attribute prefix, child elements by name in document order, its text /// under the text key. Child elements of one name are an array when they repeat, when an arrays path names them, or /// when the schema lets them repeat. With a schema, numbers and booleans are JSON numbers and booleans, and an element /// of element content is an object even when empty. Comments and processing instructions are left out; CDATA is text. /// internal sealed class XmlToJson { internal static readonly XNamespace Xsi = "http://www.w3.org/2001/XMLSchema-instance"; private static readonly JsonSerializerOptions Compact = new() { Encoder = JavaScriptEncoder.Create(UnicodeRanges.All), }; private static readonly JsonSerializerOptions Indented = new(Compact) { WriteIndented = true }; private readonly XmlJsonOptions _options; private readonly ArrayPaths _arrays; private readonly SchemaModel? _schema; public XmlToJson(XmlJsonOptions options) { _options = options; _arrays = new ArrayPaths(options.Arrays); var set = options.SchemaSet ?? (options.Schema is { } path ? SchemaResolver.Load("xmljson", path, options.SchemaRoot) : null); _schema = set is null ? null : new SchemaModel(set); } /// Reads through and returns the JSON tree. public JsonObject Convert(byte[] xml) => Convert(SafeXml.Load(xml, XmlLimits.Default, LoadOptions.PreserveWhitespace)); /// The JSON tree of . public JsonObject Convert(XDocument document) { var root = document.Root ?? throw new InvalidOperationException("xmljson: the XML document has no root element."); var path = new List<(string Local, string Written)>(); return new JsonObject { [JsonName(root)] = Element(root, path, _schema?.Root(root.Name)) }; } /// The JSON text of , UTF-8. public byte[] Write(JsonNode tree) => Encoding.UTF8.GetBytes(tree.ToJsonString(_options.Indent ? Indented : Compact)); private JsonNode? Element(XElement element, List<(string Local, string Written)> path, SchemaElement? declared) { path.Add((element.Name.LocalName, PrefixedName(element))); try { var attributes = Attributes(element, declared, path, out var nil); var children = element.Elements().ToList(); if (attributes.Count == 0 && children.Count == 0 && !SchemaModel.IsComplexContent(declared?.Type)) return nil ? null : SchemaModel.Typed(Text(element, onlyChild: true), SchemaModel.TextDatatype(declared?.Type), Where(path)); if (attributes.Count == 0 && children.Count == 0 && nil) return null; // Beside other attributes a nil is kept as the attribute it is, so nothing of the element is lost. if (nil) attributes.Add((_options.AttributePrefix + AttributeName(element, element.Attribute(Xsi + "nil")!), JsonValue.Create(element.Attribute(Xsi + "nil")!.Value))); var result = new JsonObject(); foreach (var (name, value) in attributes) result[name] = value; var groups = children.GroupBy(JsonName, StringComparer.Ordinal).ToList(); // A plural wrapper holds child elements of one name only; its own attributes do not matter. var pluralWrapper = _options.Plural && groups.Count == 1 && Internal.Plural.IsPair(element.Name.LocalName, children[0].Name.LocalName); foreach (var group in groups) { var members = group.ToList(); var child = ChildDeclaration(declared, members[0], path); path.Add((members[0].Name.LocalName, PrefixedName(members[0]))); var isArray = members.Count > 1 || _arrays.Matches(path) || child?.Repeats == true || pluralWrapper; path.RemoveAt(path.Count - 1); if (isArray) { var array = new JsonArray(); foreach (var member in members) array.Add(Element(member, path, ChildDeclaration(declared, member, path))); result[group.Key] = array; } else { result[group.Key] = Element(members[0], path, child); } } var text = Text(element, onlyChild: children.Count == 0); if (text.Length > 0) result[_options.TextKey] = SchemaModel.Typed(text, SchemaModel.TextDatatype(declared?.Type), Where(path)); return result; } finally { path.RemoveAt(path.Count - 1); } } /// /// The declaration of in the content of its parent; an error when the schema has no place /// for it. null without a schema. /// private SchemaElement? ChildDeclaration(SchemaElement? parent, XElement child, List<(string Local, string Written)> path) { if (_schema is null || parent is null) return null; return _schema.Child(parent, child.Name) ?? throw new InvalidOperationException( $"xmljson: {Where(path)} holds '{child.Name.LocalName}', which its content in the schema has no place for."); } /// /// The attributes as JSON keys and values. xsi:nil="true" makes true and is not an /// attribute of the result; namespace declarations are attributes under only. /// private List<(string Name, JsonNode? Value)> Attributes(XElement element, SchemaElement? declared, List<(string Local, string Written)> path, out bool nil) { nil = false; var result = new List<(string, JsonNode?)>(); foreach (var attribute in element.Attributes()) { if (attribute.Name == Xsi + "nil" && attribute.Value.Trim() is "true" or "1") { nil = true; continue; } if (attribute.IsNamespaceDeclaration) { if (_options.Namespaces == XmlJsonNamespaces.Keep) result.Add((_options.AttributePrefix + (attribute.Name.Namespace == XNamespace.None ? "xmlns" : "xmlns:" + attribute.Name.LocalName), JsonValue.Create(attribute.Value))); continue; } var name = AttributeName(element, attribute); result.Add((_options.AttributePrefix + name, SchemaModel.Typed(attribute.Value, SchemaModel.AttributeDatatype(declared?.Type, attribute.Name), Where(path) + "/@" + name))); } return result; } private string AttributeName(XElement element, XAttribute attribute) { if (_options.Namespaces == XmlJsonNamespaces.Drop || attribute.Name.Namespace == XNamespace.None) return attribute.Name.LocalName; var prefix = element.GetPrefixOfNamespace(attribute.Name.Namespace); return string.IsNullOrEmpty(prefix) ? attribute.Name.LocalName : prefix + ":" + attribute.Name.LocalName; } /// The element's name as a JSON key: the written name, or the local name under . private string JsonName(XElement element) => _options.Namespaces == XmlJsonNamespaces.Drop ? element.Name.LocalName : PrefixedName(element); private static string PrefixedName(XElement element) { if (element.Name.Namespace == XNamespace.None) return element.Name.LocalName; var prefix = element.GetPrefixOfNamespace(element.Name.Namespace); return string.IsNullOrEmpty(prefix) ? element.Name.LocalName : prefix + ":" + element.Name.LocalName; } private static string Where(List<(string Local, string Written)> path) => "/" + string.Join('/', path.Select(p => p.Written)); /// /// The element's own text: every text and CDATA node in order. Beside child elements a text node of white space /// only is layout and is left out; an element without children keeps its text as written. /// private static string Text(XElement element, bool onlyChild) { var text = new StringBuilder(); foreach (var node in element.Nodes().OfType()) { if (!onlyChild && string.IsNullOrWhiteSpace(node.Value)) continue; text.Append(node.Value); } return text.ToString(); } } Path: redb-route/redb.Route.DataFormats.XmlJson/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.DataFormats.XmlJson/README.md ---- # redb.Route.DataFormats.XmlJson > Documentation and articles: XML to JSON and back for redb.Route when there is no class for the document, as Apache Camel's `xmljson`. ## When a class exists, use it The typed path stays the recommended one: it validates, it names every field, and the compiler checks the mapping. ```csharp From("file://in?include=*.xml") .Unmarshal("application/xml") // XML to the class .Marshal("application/json") // the class to JSON .To("http://partner/orders"); ``` This package is for documents without a class: a partner format you only pass on, a schema too large to map by hand (UBL, ebMS), or a gateway that turns any XML into JSON for a JavaScript consumer. ## The JSON it writes The notation is Json.NET's, so .NET and Java consumers read it without setup: | XML | JSON | |---|---| | `5` | `{"a": "5"}` | | `` | `{"a": ""}` | | `` | `{"a": null}` | | `x` | `{"a": {"@id": "1", "#text": "x"}}` | | `12` | `{"o": {"i": ["1", "2"]}}` | | `` | `{"s:Envelope": {"@xmlns:s": "urn:s", ...}}` | - The root element is the one key of the result. - Comments and processing instructions are left out; CDATA is text; white space between child elements is layout. - `namespaces=Drop` writes local names (`"Envelope"`) and leaves the declarations out. - `textKey` and `attributePrefix` change `#text` and `@` (`$` for a WSO2 Micro Integrator consumer). - The writer escapes HTML-sensitive characters (`<` as `\u003C`): the same JSON for any parser, and safe if the JSON ever lands inside an HTML page. ## Which elements are arrays One element written as an object and two as an array is the problem every hand-written mapper solves. xmljson takes the answer from these, strongest first: 1. **`arrays=`**: element paths that are always an array, `/Order/Items/Item` from the root or `//Item` at any depth. A step with a prefix (`//x:Item`) compares with the name as the document writes it. It adds arrays the schema does not know (content under `xs:any`). 2. **The schema** (`schema=`): an element repeats when its `maxOccurs`, or that of an enclosing `sequence`, `choice` or group, is above 1. Groups, extension, substitution groups and recursive types are followed. With a schema, numbers and `xs:boolean` are JSON numbers and booleans (a string type keeps `"007"` as text), and an element of element content is an object even when empty. 3. **The plural rule** (`plural=true`, off by default): a parent named as the English plural of its children's name (`Incidents` holding only `Incident`) holds a list. Regular plurals and a short irregular list; silent on any other name. Limits: a singular ending in `-us` also reads as a plural without the `s` (`Status` / `Statu`), and JSON to XML picks one singular (`Movies` gives `Movy`). 4. **Otherwise**, the document itself: a repeat is an array, a single element an object. `check` warns about a format with neither a schema nor `arrays=`. The schema reader reads a schema and its imports from the package only, never from the network: `schemaRoot=` is the directory imports may reach, relative to the schema's own directory (`..` for UBL's `maindoc/` importing `../common/`). A schema's own DOCTYPE is skipped (W3C's xmldsig schema, imported by WS-Security, starts with one); message documents with a DTD are refused. ## JSON to XML - Without a schema: a key is an element, `@` keys are attributes (`@xmlns:p` declares a namespace), `#text` the text, an array the element repeated, `null` an `xsi:nil` element. `root=` names the root element; without it the JSON has one top-level key. A key that is not an XML name, an undeclared prefix or an array inside an array is an error naming the JSON path: nothing is renamed or dropped silently. A `null` attribute is left out, as an attribute cannot be nil. - With a schema, the schema decides: the namespace of every element and attribute, the order of children (whatever the order of the keys), the branch of a choice, numbers in the lexical form of their type (`1e3` as `1000` for a decimal). Prefixes come from the JSON's `@xmlns:p`, then `prefixes=`, then `ns0`, `ns1`. A key the schema has no place for, two branches of one choice, or `null` where not nillable is an error. Whether every required element is present is `validateXsd`'s job: put it after the step. ## In code ```csharp context.AddXmlJsonDataFormat(); // the default instance, named "xmljson" From("direct://in") .MarshalXmlJson(o => { o.Schema = "schemas/order.xsd"; o.Arrays.Add("//Tag"); }) // XML to JSON .UnmarshalXmlJson(o => o.Schema = "schemas/order.xsd"); // JSON to XML ``` `UnmarshalXmlJson()` from an XML body gives the JSON tree. The other targets are `string`, `byte[]`, `XDocument`, `XElement` and `XmlDocument`. After `Marshal` the content type is `application/json`, after `Unmarshal` `application/xml`; the format itself is registered under `application/x-xmljson` and the name `xmljson`. ## In markup A registered format is shared and takes no options on the step, so options go on a named instance in `context.xml` or on the per-step `type=` form: ```xml ``` | Attribute | Meaning | |---|---| | `schema` | the XSD, a package resource as for `validateXsd` | | `schemaRoot` | where imports may read from, relative to the schema's directory | | `arrays` | element paths, comma-separated | | `plural` | `true` / `false` | | `namespaces` | `Keep` / `Drop` | | `prefixes` | `prefix=uri` pairs, comma-separated | | `root` | the root element of JSON to XML | | `textKey`, `attributePrefix` | default `#text` and `@` | | `indent` | `true` / `false` | The schema path resolves on the first message of each route context through the context's resource resolver (in a Tsak package, the package root), and the compiled schema is kept for that context. A missing or broken schema therefore shows at the first message: run `check` before deploying. ## What `check` and `pack` verify For an xmljson format in markup, always: the schema is a file the package ships, each `arrays=` path is well formed, and a format with neither a schema nor `arrays=` is warned. With `--bin` (the build output holds this package) the format's own check, `XmlJsonPackageCheck`, runs as well: - the schema compiles with its imports, read the way the format reads it at run time; - each `arrays=` path leads through the schema's structure, from a global element for `/Order/Item` and from any element for `//Lines/Line`; a path that breaks is warned at the step where it breaks (`'Line' is not a child of 'Order'`), and a path into `xs:any` content passes, since that is where `arrays=` is needed; - `xs:any` and mixed content in the schema are flagged; - with `plural=true`, the parent/child pairs the rule reads as lists are named, and those where the schema allows one child only. Not checked: an instance configured in code (`AddXmlJsonDataFormat(o => ...)` used as `format="xmljson"`), whose options the package does not show. ## Not in this version - Mixed content without loss (text between child elements is joined into `#text`), comments, processing instructions, CDATA as distinct from text. - Polymorphism by `xsi:type`, `xs:redefine` / `xs:override`, XSD 1.1, identity constraints. - Numbers and dates guessed without a schema. - A lenient mode for unknown JSON keys. - Streaming of very large documents: the conversion builds the document in memory, within the XML structure limits. Path: redb-route/redb.Route.DataFormats.XmlJson/XmlJsonDataFormat.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.DataFormats.XmlJson/XmlJsonDataFormat.cs ---- using redb.Route.Validation; using System.Runtime.CompilerServices; using System.Text; using System.Text.Json.Nodes; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.DataFormats.XmlJson.Internal; namespace redb.Route.DataFormats.XmlJson; /// /// XML to JSON and back without a class, as Apache Camel's xmljson: Marshal turns an XML body into JSON, /// Unmarshal turns a JSON body into XML (or, to a , an XML body into the JSON tree). The /// notation is Json.NET's (@attribute, #text); which elements are arrays comes from the schema, the arrays /// paths, the opt-in plural rule, and otherwise from the document itself (a repeat is an array). /// /// When a class exists for the document, the typed path stays the recommended one: Unmarshal<Order>() from /// XML, then Marshal() to JSON. /// /// /// The schema path resolves through the route context's resource resolver, as validateXsd does, on the first /// message of each context; the compiled schema is kept for that context. /// /// public sealed class XmlJsonDataFormat : IMessageDataFormat { /// Content type the format is registered under, beside the name xmljson. public const string DefaultContentType = "application/x-xmljson"; /// The name the format answers to in markup: <marshal format="xmljson"/>. public const string Name = "xmljson"; private readonly XmlJsonOptions _options; private readonly ConditionalWeakTable _byContext = new(); private Converters? _withoutContext; /// Creates the format with default options; markup sets its properties. public XmlJsonDataFormat() : this(null) { } /// Creates the format with the given options (defaults when null). public XmlJsonDataFormat(XmlJsonOptions? options) => _options = options ?? new XmlJsonOptions(); /// The options in effect. public XmlJsonOptions Options => _options; // ── Markup properties: the options in the string forms an attribute can carry ───────────── /// The schema path (). public string? Schema { get => _options.Schema; set => _options.Schema = value; } /// The directory imports may read from, relative to the schema's directory (). public string? SchemaRoot { get => _options.SchemaRoot; set => _options.SchemaRoot = value; } /// The arrays paths, comma-separated: //Item,/Order/Tag (). public string? Arrays { get => _options.Arrays.Count == 0 ? null : string.Join(',', _options.Arrays); set { _options.Arrays.Clear(); foreach (var path in (value ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) _options.Arrays.Add(path); } } /// Namespace prefixes, comma-separated prefix=uri pairs: o=urn:orders (). public string? Prefixes { get => _options.Prefixes.Count == 0 ? null : string.Join(',', _options.Prefixes.Select(p => p.Key + "=" + p.Value)); set { _options.Prefixes.Clear(); foreach (var pair in (value ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var equals = pair.IndexOf('='); if (equals <= 0 || equals == pair.Length - 1) throw new ArgumentException($"xmljson prefixes '{pair}' is not prefix=uri, as in o=urn:orders.", nameof(value)); _options.Prefixes[pair[..equals].Trim()] = pair[(equals + 1)..].Trim(); } } } /// The plural-wrapper rule (). public bool Plural { get => _options.Plural; set => _options.Plural = value; } /// How names carry their namespaces (). public XmlJsonNamespaces Namespaces { get => _options.Namespaces; set => _options.Namespaces = value; } /// The text key (). public string TextKey { get => _options.TextKey; set => _options.TextKey = value; } /// The attribute prefix (). public string AttributePrefix { get => _options.AttributePrefix; set => _options.AttributePrefix = value; } /// The root element of JSON to XML (). public string? Root { get => _options.Root; set => _options.Root = value; } /// Whether the output is indented (). public bool Indent { get => _options.Indent; set => _options.Indent = value; } // ── IMessageSerializer ──────────────────────────────────────────────────────────────────── /// public string ContentType => DefaultContentType; /// public IReadOnlyCollection MediaTypes => [DefaultContentType]; /// public bool WrapsBytes => true; /// XML to JSON, without a route context: the schema path resolves through the default resolver. public byte[] Serialize(T value) => ToJson(For(null), Xml(value)); /// public T? Deserialize(byte[] data) => (T?)Deserialize(data, typeof(T)); /// /// Without a route context: JSON to XML as (string, byte[], /// , ), or XML to the JSON tree for a type. /// public object? Deserialize(byte[] data, Type type) { ArgumentNullException.ThrowIfNull(data); return Read(For(null), data, type); } // ── IMessageDataFormat ──────────────────────────────────────────────────────────────────── /// public ValueTask MarshalAsync(IExchange exchange, CancellationToken ct = default) { var body = exchange.In.Body; if (body is null) return ValueTask.CompletedTask; exchange.In.Body = ToJson(For(exchange.Context), Xml(body)); exchange.In.ContentType = "application/json"; exchange.In.Headers["Content-Type"] = "application/json"; return ValueTask.CompletedTask; } /// public async ValueTask UnmarshalAsync(IExchange exchange, Type targetType, CancellationToken ct = default) { var bytes = exchange.In.Body switch { null => null, byte[] b => b, string s => Encoding.UTF8.GetBytes(s), Stream stream => await ReadAll(stream, ct).ConfigureAwait(false), JsonNode node => Encoding.UTF8.GetBytes(node.ToJsonString()), var other => throw new InvalidOperationException( $"xmljson: cannot unmarshal a {other.GetType().Name} body; it reads JSON (or XML, to a JsonNode) as bytes, a string or a stream."), }; if (bytes is null) return; exchange.In.Body = Read(For(exchange.Context), bytes, targetType); var contentType = typeof(JsonNode).IsAssignableFrom(targetType) ? "application/json" : "application/xml"; exchange.In.ContentType = contentType; exchange.In.Headers["Content-Type"] = contentType; } // ── Conversion ──────────────────────────────────────────────────────────────────────────── private static byte[] ToJson(Converters converters, byte[] xml) => converters.ToJson.Write(converters.ToJson.Convert(xml)); private static object? Read(Converters converters, byte[] data, Type type) { if (typeof(JsonNode).IsAssignableFrom(type)) return converters.ToJson.Convert(data); var document = converters.ToXml.Convert(data); if (type == typeof(XDocument) || type == typeof(object)) return document; if (type == typeof(XElement)) return document.Root; var bytes = converters.ToXml.Write(document); if (type == typeof(byte[])) return bytes; if (type == typeof(string)) return Encoding.UTF8.GetString(bytes); if (type == typeof(XmlDocument)) return SafeXml.LoadDocument(bytes, XmlLimits.Default); throw new InvalidOperationException( $"xmljson: cannot unmarshal to {type.Name}; the targets are string, byte[], XDocument, XElement, XmlDocument (XML from JSON) and JsonNode (JSON from XML). For a class, unmarshal with the JSON or XML format to it."); } /// The XML bytes of a body: bytes or text as they are, an XML tree written out. private static byte[] Xml(object? body) => body switch { null => [], byte[] bytes => bytes, string text => Encoding.UTF8.GetBytes(text), XDocument document => Encoding.UTF8.GetBytes(document.ToString(SaveOptions.DisableFormatting)), XElement element => Encoding.UTF8.GetBytes(element.ToString(SaveOptions.DisableFormatting)), XmlDocument document => Encoding.UTF8.GetBytes(document.OuterXml), Stream stream => ReadAllSync(stream), var other => throw new InvalidOperationException( $"xmljson: cannot marshal a {other.GetType().Name} body; it reads XML as bytes, a string, a stream or an XML tree. For a class, marshal it with the JSON format."), }; private static byte[] ReadAllSync(Stream stream) { using var buffer = new MemoryStream(); stream.CopyTo(buffer); return buffer.ToArray(); } private static async Task ReadAll(Stream stream, CancellationToken ct) { using var buffer = new MemoryStream(); await stream.CopyToAsync(buffer, ct).ConfigureAwait(false); return buffer.ToArray(); } /// The converters of a context: its schema resolved once through that context's resource resolver. private Converters For(IRouteContext? context) { if (context is null) return _withoutContext ??= Build(null); return _byContext.GetValue(context, Build); } private Converters Build(IRouteContext? context) { var set = _options.SchemaSet; if (set is null && _options.Schema is { } schema) { set = SchemaResolver.Load("xmljson", ResourceResolution.Resolve(context, schema, "xmljson schema"), _options.SchemaRoot); } var resolved = Copy(set); return new Converters(new XmlToJson(resolved), new JsonToXml(resolved)); } /// The options with the compiled schema set in place of the path, so the converters do not load it again. private XmlJsonOptions Copy(XmlSchemaSet? set) { var copy = new XmlJsonOptions { TextKey = _options.TextKey, AttributePrefix = _options.AttributePrefix, Namespaces = _options.Namespaces, Plural = _options.Plural, Root = _options.Root, Indent = _options.Indent, SchemaSet = set, }; foreach (var path in _options.Arrays) copy.Arrays.Add(path); foreach (var (prefix, uri) in _options.Prefixes) copy.Prefixes[prefix] = uri; return copy; } private sealed record Converters(XmlToJson ToJson, JsonToXml ToXml); } Path: redb-route/redb.Route.DataFormats.XmlJson/XmlJsonOptions.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.DataFormats.XmlJson/XmlJsonOptions.cs ---- namespace redb.Route.DataFormats.XmlJson; /// How element and attribute names carry their XML namespaces in JSON. public enum XmlJsonNamespaces { /// /// Names keep the prefix of the document ("soap:Envelope"), and namespace declarations appear as attributes /// where the document declares them ("@xmlns:soap": "uri"). /// Keep, /// Names are local names ("Envelope"), and namespace declarations are left out. Drop, } /// Options of the xmljson data format. public sealed class XmlJsonOptions { /// /// The key of an element's text when the element also has attributes or child elements. Default #text, as /// Json.NET writes it; $ matches WSO2 Micro Integrator. /// public string TextKey { get; set; } = "#text"; /// The prefix of an attribute's key. Default @, as Json.NET and WSO2 write it. public string AttributePrefix { get; set; } = "@"; /// How names carry their namespaces. Default . public XmlJsonNamespaces Namespaces { get; set; } = XmlJsonNamespaces.Keep; /// /// Paths of the elements that are always a JSON array, even when the document holds one of them: /// /Order/Items/Item from the root, //Line at any depth. A step is a local name, or a /// prefix:name compared with the name as the document writes it. /// public IList Arrays { get; } = new List(); /// /// The plural-wrapper rule, off by default: a parent named as the English plural of its children's name /// (Incidents holding only Incident) holds a list, so its children are an array even when there is /// one. Regular plurals (-s, -es, -ies) and a short list of irregular ones /// (Children / Child); silent on every other name. /// public bool Plural { get; set; } /// /// The root element of JSON to XML. Without it the JSON is an object of one key, and that key is the root; with it /// the whole JSON is the root's content. A name with a prefix (o:Order) needs the prefix declared by an /// @xmlns:o key. /// public string? Root { get; set; } /// /// Prefixes for the namespaces of JSON to XML by a schema, prefix to namespace URI ("o" = "urn:orders"). /// A namespace the JSON declares with an @xmlns:p key keeps that prefix; one neither declares gets /// ns0, ns1 and so on. Every declaration goes on the root element. /// public IDictionary Prefixes { get; } = new Dictionary(StringComparer.Ordinal); /// Whether the output, JSON or XML, is indented. Default false. public bool Indent { get; set; } /// /// Path of the XSD that describes the documents: which elements repeat, the types of values, nillable elements. /// Its imports and includes are read from files under , never from the network. /// public string? Schema { get; set; } /// /// The directory the imports and includes of may read from; a relative one is relative to the /// schema's own directory (.. for a schema in maindoc/ that imports ../common/). Default: the /// directory of the schema itself. /// public string? SchemaRoot { get; set; } /// A schema set built in code, in place of ; it is compiled when the format first uses it. public System.Xml.Schema.XmlSchemaSet? SchemaSet { get; set; } } Path: redb-route/redb.Route.DataFormats.XmlJson/XmlJsonPackageCheck.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.DataFormats.XmlJson/XmlJsonPackageCheck.cs ---- using redb.Route.Validation; using System.Xml; using System.Xml.Linq; using System.Xml.Schema; using redb.Route.DataFormats.XmlJson.Internal; using redb.Route.Xml.Packaging; namespace redb.Route.DataFormats.XmlJson; /// /// The xmljson checks of check and pack that need the format's own code, run with --bin: the schema /// compiles with the reader the format uses at run time; each arrays= path leads through the schema's structure, /// from a global element for /a/b and from any element for //a/b; xs:any and mixed content are /// flagged; with plural=true the parent/child pairs the rule reads as lists are named. The checks that need no /// code of the format (the schema is in the package, the paths are well formed) are the gate's own. /// public sealed class XmlJsonPackageCheck : IPackageCheck { private static readonly string FormatType = typeof(XmlJsonDataFormat).FullName!; /// public void Check(PackageCheckContext context) { ArgumentNullException.ThrowIfNull(context); foreach (var document in context.Documents) foreach (var element in document.Document.Descendants()) if (element.Name.LocalName is "dataFormat" or "marshal" or "unmarshal" && element.Attribute("type")?.Value is { } type && string.Equals(type.Split(',')[0].Trim(), FormatType, StringComparison.Ordinal)) CheckFormat(context, document, element); } private static void CheckFormat(PackageCheckContext context, PackageDocument document, XElement element) { if (element.Attribute("schema") is not { } schema || schema.Value.Contains("{{", StringComparison.Ordinal) || schema.Value.Contains("${", StringComparison.Ordinal) || context.Resource(schema.Value, out _) is not { } path) return; // no schema, one configuration resolves later, or one the gate already reports var name = schema.Value; XmlSchemaSet set; try { set = SchemaResolver.Load("xmljson", path, element.Attribute("schemaRoot")?.Value); } catch (Exception ex) when (ex is XmlSchemaException or XmlException or IOException or InvalidOperationException) { context.Error(document, schema, $"xmljson schema '{name}' does not compile: {ex.Message}"); return; } var facts = SchemaFacts.Of(new SchemaModel(set), set); if (element.Attribute("arrays") is { } arrays) foreach (var arraysPath in arrays.Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) if (facts.PathProblem(arraysPath) is { } problem) context.Warning(document, arrays, $"xmljson arrays path '{arraysPath}' does not lead through schema '{name}': {problem}."); if (facts.Wildcards.Count > 0) context.Warning(document, schema, $"xmljson schema '{name}' has xs:any in {Listed(facts.Wildcards)}: elements there are not described, so their arrays come from arrays= or the document."); if (facts.Mixed.Count > 0) context.Warning(document, schema, $"xmljson schema '{name}' has mixed content in {Listed(facts.Mixed)}: text between child elements is joined into one text value."); if (element.Attribute("plural") is { } plural && string.Equals(plural.Value.Trim(), "true", StringComparison.OrdinalIgnoreCase)) context.Warning(document, plural, facts.PluralPairs.Count == 0 ? $"xmljson plural=true finds no parent named as the plural of its only child in schema '{name}'; the rule changes nothing here." : $"xmljson plural=true reads {facts.PluralPairs.Count} parent/child pair(s) of schema '{name}' as lists: " + $"{Listed(facts.PluralPairs)}{(facts.PluralOnce.Count > 0 ? $"; the schema allows one child only in {Listed(facts.PluralOnce)}" : "")}."); } private static string Listed(IReadOnlyCollection names) => string.Join(", ", names.Take(5).Select(n => $"'{n}'")) + (names.Count > 5 ? $" and {names.Count - 5} more" : ""); /// What the checks read from a compiled schema, gathered in one walk over its types. private sealed class SchemaFacts { private readonly SchemaModel _model; private readonly XmlSchemaSet _set; private readonly Dictionary> _byName = new(StringComparer.Ordinal); private SchemaFacts(SchemaModel model, XmlSchemaSet set) => (_model, _set) = (model, set); public SortedSet Wildcards { get; } = new(StringComparer.Ordinal); public SortedSet Mixed { get; } = new(StringComparer.Ordinal); public SortedSet PluralPairs { get; } = new(StringComparer.Ordinal); public SortedSet PluralOnce { get; } = new(StringComparer.Ordinal); public static SchemaFacts Of(SchemaModel model, XmlSchemaSet set) { var facts = new SchemaFacts(model, set); var seen = new HashSet<(string, XmlSchemaType?)>(); var queue = new Queue<(string Name, XmlSchemaType? Type)>(); foreach (XmlSchemaElement global in set.GlobalElements.Values) queue.Enqueue((global.QualifiedName.Name, global.ElementSchemaType)); while (queue.TryDequeue(out var item)) { if (!seen.Add(item)) continue; facts.Add(item.Name, item.Type); foreach (var slot in Slots(model, item.Type)) if (slot.Declaration is { } declaration) queue.Enqueue((declaration.QualifiedName.Name, declaration.ElementSchemaType)); } return facts; } // The built-in types (xs:anyType holds a wildcard and is mixed) are the schema language's, not the author's. private static IReadOnlyList Slots(SchemaModel model, XmlSchemaType? type) => type is XmlSchemaComplexType complex && complex.QualifiedName.Namespace != XmlSchema.Namespace ? model.Slots(type) : []; private void Add(string name, XmlSchemaType? type) { if (!_byName.TryGetValue(name, out var types)) _byName[name] = types = []; types.Add(type); var slots = Slots(_model, type); var owner = type is { QualifiedName.IsEmpty: false } ? type.QualifiedName.Name : name; if (type is XmlSchemaComplexType { IsMixed: true } complex && complex.QualifiedName.Namespace != XmlSchema.Namespace) Mixed.Add(owner); if (slots.Any(s => s.Wildcard)) Wildcards.Add(owner); var children = slots.Where(s => !s.Wildcard).Select(s => s.Name.Name).Distinct(StringComparer.Ordinal).ToList(); if (children is [var child] && !slots.Any(s => s.Wildcard) && Plural.IsPair(name, child)) { PluralPairs.Add($"{name}/{child}"); if (!slots.Any(s => s.Repeats)) PluralOnce.Add($"{name}/{child}"); } } /// Why an arrays path leads nowhere in the schema; null when it leads to an element or into xs:any. public string? PathProblem(string path) { var anywhere = path.StartsWith("//", StringComparison.Ordinal); if (!anywhere && !path.StartsWith('/')) return null; // malformed: the gate's own error var written = path[(anywhere ? 2 : 1)..].Split('/'); var steps = written.Select(Local).ToArray(); if (steps.Any(s => s.Length == 0)) return null; List current = anywhere ? _byName.GetValueOrDefault(steps[0]) ?? [] : [.. _set.GlobalElements.Values.Cast() .Where(e => e.QualifiedName.Name == steps[0]).Select(e => e.ElementSchemaType)]; if (current.Count == 0) return anywhere ? $"'{written[0]}' names no element of it" : $"'{written[0]}' is not a global element of it"; for (var i = 1; i < steps.Length; i++) { var next = new List(); var open = false; foreach (var type in current) { if (type is null) { open = true; // content nothing describes continue; } foreach (var slot in Slots(_model, type)) if (slot.Wildcard) open = true; else if (slot.Name.Name == steps[i]) next.Add(slot.Declaration?.ElementSchemaType); } if (next.Count == 0) return open ? null : $"'{written[i]}' is not a child of '{written[i - 1]}'"; current = next; } return null; } private static string Local(string step) => step.Contains(':') ? step[(step.IndexOf(':') + 1)..] : step; } } Path: redb-route/redb.Route.DataFormats.XmlJson/XmlJsonRouteDefinitionExtensions.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.DataFormats.XmlJson/XmlJsonRouteDefinitionExtensions.cs ---- using redb.Route.Abstractions; using redb.Route.Extensions; namespace redb.Route.DataFormats.XmlJson; /// DSL and registration sugar for . public static class XmlJsonRouteDefinitionExtensions { /// Turns an XML body into JSON, with per-node options. public static IRouteDefinition MarshalXmlJson(this IRouteDefinition route, Action? configure = null) => route.Marshal(new XmlJsonDataFormat(Build(configure))); /// /// Turns a JSON body into XML as (string, byte[], XDocument, /// XElement, XmlDocument), or an XML body into the JSON tree for T = JsonNode. /// public static IRouteDefinition UnmarshalXmlJson(this IRouteDefinition route, Action? configure = null) => route.Unmarshal(new XmlJsonDataFormat(Build(configure))); /// /// Registers the format on the context under its content type and the name xmljson, for /// <marshal format="xmljson"/> and Marshal("xmljson"). /// public static IRouteContext AddXmlJsonDataFormat(this IRouteContext context, Action? configure = null) => context.AddDataFormat(new XmlJsonDataFormat(Build(configure)), XmlJsonDataFormat.Name); /// DI form of . public static RedbRouteBuilder AddXmlJsonDataFormat(this RedbRouteBuilder builder, Action? configure = null) => builder.AddDataFormat(new XmlJsonDataFormat(Build(configure)), XmlJsonDataFormat.Name); private static XmlJsonOptions Build(Action? configure) { var options = new XmlJsonOptions(); configure?.Invoke(options); return options; } } Path: redb-route/redb.Route.DataFormats.XmlJson/redb.Route.DataFormats.XmlJson.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.DataFormats.XmlJson/redb.Route.DataFormats.XmlJson.csproj ---- redb.Route.DataFormats.XmlJson XML to JSON and back without a class for redb.Route: the Json.NET notation (@attribute, #text), arrays known from an XSD or an explicit list of element paths, namespaces kept or dropped. esb;messaging;xml;json;xsd;dataformat;redb README.md