Path: redb-route/redb.Route.Xml/XmlRouteSchema.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.Xml/XmlRouteSchema.cs
----
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using redb.Route.Core;
namespace redb.Route.Xml;
///
/// The XSD of the route format, GENERATED from the element registry: the parser, the
/// schema and the catalog read one list, so they cannot drift apart. The schema covers the
/// container skeleton (<routes>/<context>, <bean>,
/// <route>) plus every registered element with its attributes, enum hints and
/// content model. Package contributions appear automatically; the endpoint children of the
/// structured form (§7.2) are open content until a component catalog supplies the scheme
/// elements. One namespace, urn:redb:route:1.0; foreign-namespace attributes are
/// tolerated (anyAttribute ##other lax), foreign elements are not.
///
public static class XmlRouteSchema
{
private const string Ns = XmlRouteLoader.Namespace;
private static readonly XNamespace Xs = "http://www.w3.org/2001/XMLSchema";
private static readonly System.Runtime.CompilerServices.ConditionalWeakTable Cache = new();
private static readonly Lazy Core = new(() => For(ElementRegistry.CreateDefault()));
/// The compiled schema of the core element set — generated and compiled once.
public static XmlSchemaSet CoreSet => Core.Value;
/// Validates against an already-compiled set (the loader's hot path).
public static IReadOnlyList<(int Line, int Column, string Message)> Validate(
XDocument document, XmlSchemaSet schema)
{
ArgumentNullException.ThrowIfNull(document);
ArgumentNullException.ThrowIfNull(schema);
var problems = new List<(int, int, string)>();
var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = schema };
settings.ValidationEventHandler += (_, e) =>
problems.Add((e.Exception?.LineNumber ?? 0, e.Exception?.LinePosition ?? 0, e.Message));
using var reader = XmlReader.Create(document.CreateReader(), settings);
while (reader.Read()) { }
return problems;
}
/// The compiled schema for a registry (cached per registry instance).
public static XmlSchemaSet For(ElementRegistry registry)
{
ArgumentNullException.ThrowIfNull(registry);
return Cache.GetValue(registry, r =>
{
var set = new XmlSchemaSet();
using var reader = Generate(r).CreateReader();
set.Add(Ns, reader);
set.Compile();
return set;
});
}
///
/// Validates a document against the registry's schema. Returns one positioned message per
/// problem; an empty list means the document is schema-valid.
///
public static IReadOnlyList<(int Line, int Column, string Message)> Validate(
XDocument document, ElementRegistry registry)
{
ArgumentNullException.ThrowIfNull(document);
var schema = For(registry);
var problems = new List<(int, int, string)>();
var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = schema };
settings.ValidationEventHandler += (_, e) =>
problems.Add((e.Exception?.LineNumber ?? 0, e.Exception?.LinePosition ?? 0, e.Message));
using var reader = XmlReader.Create(document.CreateReader(), settings);
while (reader.Read()) { }
return problems;
}
///
/// Validates against a schema that also knows the component catalog: the §7.2 endpoint
/// children become a STRICT set of scheme elements with typed, enum-hinted options.
///
public static IReadOnlyList<(int Line, int Column, string Message)> Validate(
XDocument document, ElementRegistry registry, IReadOnlyList catalog)
{
ArgumentNullException.ThrowIfNull(document);
var set = new XmlSchemaSet();
using (var reader = Generate(registry, catalog).CreateReader())
set.Add(Ns, reader);
set.Compile();
var problems = new List<(int, int, string)>();
var settings = new XmlReaderSettings { ValidationType = ValidationType.Schema, Schemas = set };
settings.ValidationEventHandler += (_, e) =>
problems.Add((e.Exception?.LineNumber ?? 0, e.Exception?.LinePosition ?? 0, e.Message));
using var validating = XmlReader.Create(document.CreateReader(), settings);
while (validating.Read()) { }
return problems;
}
/// Generates the schema document for a registry — also the file the tooling ships.
public static XDocument Generate(ElementRegistry registry, IReadOnlyList? catalog = null)
{
ArgumentNullException.ThrowIfNull(registry);
var contributions = registry.Contributions
.OrderBy(c => c.Name, StringComparer.Ordinal)
.ToList();
var stepNames = contributions
.Where(c => c.Kind is XmlElementKind.Step or XmlElementKind.Scope or XmlElementKind.Branching)
.Select(c => c.Name)
.ToList();
var schema = new XElement(Xs + "schema",
new XAttribute("targetNamespace", Ns),
new XAttribute("elementFormDefault", "qualified"),
new XAttribute(XNamespace.Xmlns + "xs", Xs),
new XAttribute(XNamespace.Xmlns + "r", Ns));
// The step group: every registered step/scope/branching element.
schema.Add(new XElement(Xs + "group",
new XAttribute("name", "step"),
new XElement(Xs + "choice",
stepNames.Select(StepParticle))));
foreach (var contribution in contributions)
schema.Add(contribution.Name == BeanStep
? NamedType(BeanStepType, contribution.Spec, catalog)
: GlobalElement(contribution.Spec, catalog));
schema.Add(BeanElement());
schema.Add(BeanListType());
if (catalog is not null)
{
schema.Add(OtherSideTypes());
// One type per (component, side), referenced from every endpoint position (see
// SchemeElement): a connector's options are declared once, not once per position.
foreach (var endpointType in EndpointTypes(catalog))
schema.Add(endpointType);
}
schema.Add(RouteElement(catalog));
if (contributions.Any(c => c.Name == "onException"))
schema.Add(RouteConfigurationElement());
schema.Add(RoutesElement(contributions));
schema.Add(ContextElement(contributions));
return new XDocument(schema);
}
// ── the container skeleton (owned by the loader, versioned with it) ──────
private static XElement RoutesElement(IReadOnlyList contributions)
{
var containerHandlers = new[] { "onException", "intercept", "interceptFrom", "interceptSendToEndpoint", "onCompletion" }
.Where(n => contributions.Any(c => c.Name == n));
var topLevel = contributions
.Where(c => c.Kind == XmlElementKind.TopLevel)
.Select(c => c.Name);
return new XElement(Xs + "element", new XAttribute("name", "routes"),
new XElement(Xs + "complexType",
new XElement(Xs + "choice",
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"),
new XElement(Xs + "element", new XAttribute("ref", "r:bean")),
new XElement(Xs + "element", new XAttribute("ref", "r:route")),
containerHandlers.Select(n => new XElement(Xs + "element", new XAttribute("ref", "r:" + n))),
RouteConfigurationRef(contributions),
topLevel.Select(n => new XElement(Xs + "element", new XAttribute("ref", "r:" + n)))),
new XElement(Xs + "attribute", new XAttribute("name", "version"), new XAttribute("type", "xs:string")),
ForeignAttributes()));
}
///
/// <routeConfiguration id="…">: <onException> blocks shared by the routes of the context.
/// Part of the skeleton, as <route> is; present whenever <onException> is.
///
private static XElement RouteConfigurationElement()
=> new(Xs + "element", new XAttribute("name", XmlRouteLoader.RouteConfigurationElement),
new XElement(Xs + "complexType",
new XElement(Xs + "sequence",
new XElement(Xs + "element", new XAttribute("ref", "r:onException"),
new XAttribute("minOccurs", "1"), new XAttribute("maxOccurs", "unbounded"))),
Attribute(new AttributeSpec("id", AttributeType.String)),
ForeignAttributes()));
private static IEnumerable RouteConfigurationRef(IReadOnlyList contributions)
=> contributions.Any(c => c.Name == "onException")
? [new XElement(Xs + "element", new XAttribute("ref", "r:" + XmlRouteLoader.RouteConfigurationElement))]
: [];
private static XElement ContextElement(IReadOnlyList contributions)
=> new(Xs + "element", new XAttribute("name", "context"),
new XElement(Xs + "complexType",
new XElement(Xs + "choice",
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"),
new XElement(Xs + "element", new XAttribute("name", "components"),
new XElement(Xs + "complexType",
new XElement(Xs + "sequence",
new XElement(Xs + "element", new XAttribute("name", "component"),
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"),
new XElement(Xs + "complexType",
Attribute(new AttributeSpec("type", AttributeType.TypeName, Required: true)),
ForeignAttributes()))))),
new XElement(Xs + "element", new XAttribute("ref", "r:bean")),
new XElement(Xs + "element", new XAttribute("name", "onInit"),
new XElement(Xs + "complexType", StepGroup(), ForeignAttributes())),
RouteConfigurationRef(contributions),
contributions
.Where(c => c.Kind == XmlElementKind.ContextLevel)
.Select(c => new XElement(Xs + "element", new XAttribute("ref", "r:" + c.Name))))));
private static XElement BeanElement()
=> new(Xs + "element", new XAttribute("name", "bean"),
new XElement(Xs + "complexType",
new XElement(Xs + "choice",
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"),
// A slot holds exactly one of value=, ref=, a nested , a ; the
// schema offers all four and the parser (BeanModel) rejects a second one.
new XElement(Xs + "element", new XAttribute("name", "property"),
BeanSlot(Attribute(new AttributeSpec("key", AttributeType.String, Required: true)))),
new XElement(Xs + "element", new XAttribute("name", "constructorArg"),
// type= names the parameter the value binds to (Spring constructor-arg type):
// the constructor or factory method is then the one with exactly that signature.
BeanSlot(Attribute(new AttributeSpec("type", AttributeType.TypeName))))),
// name is required on a registered bean and absent on a nested anonymous one —
// context-dependent, so the parser enforces it and the schema stays permissive.
Attribute(new AttributeSpec("name", AttributeType.String)),
Attribute(new AttributeSpec("type", AttributeType.TypeName, Required: true)),
// A public static creator instead of a constructor; constructorArg values are its
// arguments (X509CertificateLoader.LoadPkcs12FromFile is the shape this serves).
Attribute(new AttributeSpec("factoryMethod", AttributeType.String)),
ForeignAttributes()));
private static XElement BeanSlot(params XElement[] attributes)
=> new(Xs + "complexType",
new XElement(Xs + "choice",
new XAttribute("minOccurs", "0"),
new XElement(Xs + "element", new XAttribute("ref", "r:bean")),
new XElement(Xs + "element", new XAttribute("name", "list"), new XAttribute("type", "r:beanList"))),
attributes,
Attribute(new AttributeSpec("value", AttributeType.String)),
// A bean registered earlier, by its bare name (no '#': the attribute already says it).
Attribute(new AttributeSpec("ref", AttributeType.String)),
ForeignAttributes());
///
/// A named type because a list nests: its items are text values, references, anonymous beans
/// and further lists. of= names the element type where the target does not (a constructor).
///
private static XElement BeanListType()
=> new(Xs + "complexType", new XAttribute("name", "beanList"),
new XElement(Xs + "choice",
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"),
new XElement(Xs + "element", new XAttribute("name", "value"), new XAttribute("type", "xs:string")),
new XElement(Xs + "element", new XAttribute("name", "ref"),
new XElement(Xs + "complexType",
Attribute(new AttributeSpec("bean", AttributeType.String, Required: true)),
ForeignAttributes())),
new XElement(Xs + "element", new XAttribute("ref", "r:bean")),
new XElement(Xs + "element", new XAttribute("name", "list"), new XAttribute("type", "r:beanList"))),
Attribute(new AttributeSpec("of", AttributeType.TypeName)),
ForeignAttributes());
private static XElement RouteElement(IReadOnlyList? catalog)
=> new(Xs + "element", new XAttribute("name", "route"),
new XElement(Xs + "complexType",
new XElement(Xs + "sequence",
new XElement(Xs + "element", new XAttribute("name", "from"),
new XElement(Xs + "complexType",
EndpointContent(catalog, EndpointRole.Consumer),
Attribute(new AttributeSpec("uri", AttributeType.Uri)),
ForeignAttributes())),
StepGroup()),
Attribute(new AttributeSpec("id", AttributeType.String)),
Attribute(new AttributeSpec("description", AttributeType.String)),
Attribute(new AttributeSpec("autoStart", AttributeType.Bool)),
Attribute(new AttributeSpec("cluster", AttributeType.Bool)),
Attribute(new AttributeSpec("messageHistory", AttributeType.Bool)),
Attribute(new AttributeSpec("tracing", AttributeType.Bool)),
Attribute(new AttributeSpec("processingTimeout", AttributeType.Duration)),
Attribute(new AttributeSpec("routePolicy", AttributeType.Reference)),
Attribute(new AttributeSpec("routeConfigurationId", AttributeType.String)),
Attribute(new AttributeSpec("enabled", AttributeType.String)),
ForeignAttributes()));
// ── the step (amended 2026-11-05) ────────────────────────────────
// The one element name with two content models: the global is the declaration (, ,
// nested bean values); the step is declared locally in the step group with its own
// type. Two global declarations of one name would make the schema invalid, so the special case lives here only.
private const string BeanStep = "bean";
private const string BeanStepType = "beanStep";
private static XElement StepParticle(string name)
=> name == BeanStep
? new XElement(Xs + "element", new XAttribute("name", BeanStep), new XAttribute("type", "r:" + BeanStepType))
: new XElement(Xs + "element", new XAttribute("ref", "r:" + name));
private static XElement NamedType(string typeName, ElementSpec spec, IReadOnlyList? catalog)
{
var type = ComplexType(spec, catalog);
type.Add(new XAttribute("name", typeName));
return type;
}
// ── one element from its spec ────────────────────────────────────────────
private static XElement GlobalElement(ElementSpec spec, IReadOnlyList? catalog)
=> new(Xs + "element", new XAttribute("name", spec.Name), ComplexType(spec, catalog));
private static XElement ComplexType(ElementSpec spec, IReadOnlyList? catalog = null)
{
var type = new XElement(Xs + "complexType");
if (spec.AllowsTextContent)
type.Add(new XAttribute("mixed", "true"));
var contentParticles = new List();
foreach (var child in spec.Children)
contentParticles.Add(new XElement(Xs + "element",
new XAttribute("name", child.Name), ComplexType(child)));
if (spec.AllowsSteps)
contentParticles.Add(new XElement(Xs + "group", new XAttribute("ref", "r:step")));
if (spec.TakesEndpoint)
contentParticles.AddRange(EndpointParticles(catalog, EndpointRole.Producer));
if (contentParticles.Count > 0)
{
type.Add(new XElement(Xs + "choice",
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"),
contentParticles));
}
foreach (var attribute in spec.Attributes)
type.Add(Attribute(attribute));
// Id/description on every element (unless the spec already claims the names).
if (spec.Attributes.All(a => a.Name != "id"))
type.Add(Attribute(new AttributeSpec("id", AttributeType.String)));
if (spec.Attributes.All(a => a.Name != "description"))
type.Add(Attribute(new AttributeSpec("description", AttributeType.String)));
// An element whose further attributes are the options of a type it names (a serializer's Delimiter, Indented)
// takes any attribute; the loader holds each against the type's writable properties.
type.Add(spec.OpenAttributes
? new XElement(Xs + "anyAttribute", new XAttribute("namespace", "##any"), new XAttribute("processContents", "lax"))
: ForeignAttributes());
return type;
}
private static XElement StepGroup()
=> new(Xs + "group", new XAttribute("ref", "r:step"),
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"));
///
/// The §7.2 endpoint children: open lax content without a catalog; with one — the STRICT
/// set of scheme elements, each with its typed options, path/synonym attributes and open
/// family/text-option children.
///
private static IReadOnlyList EndpointParticles(IReadOnlyList? catalog, EndpointRole side)
{
if (catalog is null)
{
// skip, not lax: lax validates a child against a global declaration of the same name, and an endpoint
// child may share its name with a step (, ) or with the
// declaration. Without a catalog the schema knows no endpoint shapes; the child is normalized into the
// URI and checked strictly where the endpoint is bound (BindFromUri).
return [new XElement(Xs + "any",
new XAttribute("namespace", "##targetNamespace"),
new XAttribute("processContents", "skip"))];
}
return [.. catalog
.Where(c => HasSide(c, side))
.OrderBy(c => c.Scheme, StringComparer.Ordinal)
.Select(c => SchemeElement(c, side))];
}
///
/// Whether the component has : a component with one side ()
/// is left out of the other side's positions and gets no type for it.
///
private static bool HasSide(CatalogComponent component, EndpointRole side)
=> component.Role is null || component.Role == side;
private static XElement EndpointContent(IReadOnlyList? catalog, EndpointRole side)
=> new(Xs + "choice",
new XAttribute("minOccurs", "0"),
EndpointParticles(catalog, side));
///
/// The scheme element at an endpoint position: a reference to the ONE type carrying its options.
/// The options used to be inlined at every position that takes an endpoint (from, to,
/// enrich, pollEnrich, wireTap, interceptSendToEndpoint, both sides), so a
/// connector's whole option set stood in the schema twelve times over. That is what the editor's
/// language server pays for: it builds a content model per complex type, and the same options
/// repeated across a dozen models, each inside a choice of every scheme, is not what a schema of the
/// same size costs when it is written with named types (2026-10-08). One type per (component, side)
/// is the whole difference.
///
private static XElement SchemeElement(CatalogComponent component, EndpointRole side)
=> new(Xs + "element",
new XAttribute("name", component.Scheme),
new XAttribute("type", "r:" + EndpointTypeName(component, side)));
/// The name of the type a scheme element refers to — one per component and side.
private static string EndpointTypeName(CatalogComponent component, EndpointRole side)
=> component.Scheme + (side == EndpointRole.Producer ? "Producer" : "Consumer");
/// Every endpoint type the catalog needs, in a stable order (the scheme ordinal).
private static IEnumerable EndpointTypes(IReadOnlyList catalog)
=> catalog
.OrderBy(c => c.Scheme, StringComparer.Ordinal)
.SelectMany(c => new[] { EndpointRole.Producer, EndpointRole.Consumer }
.Where(side => HasSide(c, side))
.Select(side => EndpointType(c, side)));
private static XElement EndpointType(CatalogComponent component, EndpointRole side)
{
var type = new XElement(Xs + "complexType",
new XAttribute("name", EndpointTypeName(component, side)),
new XAttribute("mixed", "true"),
// Family entries () and long text options are open children.
new XElement(Xs + "choice",
new XAttribute("minOccurs", "0"), new XAttribute("maxOccurs", "unbounded"),
new XElement(Xs + "any",
new XAttribute("namespace", "##targetNamespace"),
new XAttribute("processContents", "lax"))));
// One declaration per attribute name, or the schema does not compile at all ("the
// attribute 'queue' already exists"): a component whose path synonym is ALSO an option
// — seda's queue, amqp's path — would declare it twice. The option wins, it carries the
// type and the enum values; the synonym only names the path.
var declared = new HashSet(component.Options.Select(o => CamelCase(o.Name)), StringComparer.Ordinal);
if (!component.PathIsText)
{
if (declared.Add("path"))
type.Add(Attribute(new AttributeSpec("path", AttributeType.String)));
if (component.PathSynonym is { Length: > 0 } synonym && declared.Add(synonym))
type.Add(Attribute(new AttributeSpec(synonym, AttributeType.String)));
}
foreach (var option in component.Options)
{
// An option only the other side reads is refused by the connector (EndpointRole). A
// strict connector simply does not declare it here, so the editor flags it as unknown;
// a lenient one takes any attribute through its wildcard, so the option is declared
// with a type no value satisfies — the editor's message names it (producerOnlyOption).
if (option.Role is { } role && role != side)
{
if (component.Lenient)
type.Add(new XElement(Xs + "attribute",
new XAttribute("name", CamelCase(option.Name)),
new XAttribute("type", "r:" + OtherSideType(role))));
continue;
}
if (option.Type is "enum" or "flags" && option.EnumValues is { Count: > 0 } members)
{
type.Add(new XElement(Xs + "attribute", new XAttribute("name", CamelCase(option.Name)),
EnumOptionType(members, flags: option.Type == "flags")));
continue;
}
type.Add(Attribute(new AttributeSpec(
CamelCase(option.Name),
option.Type switch
{
"bool" => AttributeType.Bool,
"int" => AttributeType.Int,
"long" => AttributeType.Long,
"double" => AttributeType.Double,
"duration" => AttributeType.Duration,
"enum" => AttributeType.Enum,
_ => AttributeType.String,
},
EnumValues: option.EnumValues)));
}
// The engine's own rule for an unknown parameter: a lenient connector takes it (http passes
// it on, sql reads it), a strict one refuses the endpoint — so the editor refuses the
// attribute too. A foreign-namespace attribute is never an option and stays legal.
type.Add(new XElement(Xs + "anyAttribute",
new XAttribute("namespace", component.Lenient ? "##any" : "##other"),
new XAttribute("processContents", "lax")));
return type;
}
///
/// A connector's enum option as the engine reads it: member names in any case (the option
/// converter parses with ignoreCase, and the engine's own messages write them lowercase —
/// ackMode=manual). A union of the lowercase list, which the editor offers as
/// completion, and a case-insensitive pattern, which accepts Manual as the engine does.
/// A [Flags] enum takes several members joined by commas (Tls12,Tls13), which is a
/// pattern and nothing else, so flags always take the union.
///
/// A LONG pick-one list keeps the plain member list instead. The pattern spells every member out
/// as character classes, and the catalog's 43 long options (fileExist, sortBy, postProcess,
/// operation …) sit at the same sites the short ones do: with the union for all of them the schema
/// reached 21k lines and 1.1 MB, and the editor's language server died with an out-of-memory error
/// on the first completion (2026-10-08). A long list loses the case-insensitive spelling with it:
/// the schema takes the names the catalog lists (fileExist="Append"), other cases only load
/// in the engine. pins both halves of this.
///
private static XElement EnumOptionType(IReadOnlyList members, bool flags)
{
if (!flags && members.Count > CaseInsensitiveUnionMaxMembers)
{
return new XElement(Xs + "simpleType",
new XElement(Xs + "restriction", new XAttribute("base", "xs:string"),
members.Select(m => new XElement(Xs + "enumeration", new XAttribute("value", m)))));
}
var member = "(" + string.Join("|", members.Select(AnyCase)) + ")";
var pattern = flags ? $@"{member}(\s*,\s*{member})*" : member;
return new XElement(Xs + "simpleType",
new XElement(Xs + "union",
new XElement(Xs + "simpleType",
new XElement(Xs + "restriction", new XAttribute("base", "xs:string"),
members.Select(m => new XElement(Xs + "enumeration", new XAttribute("value", m.ToLowerInvariant()))))),
new XElement(Xs + "simpleType",
new XElement(Xs + "restriction", new XAttribute("base", "xs:string"),
new XElement(Xs + "pattern", new XAttribute("value", pattern))))));
}
/// Members up to which the case-insensitive union is worth its size (see ).
private const int CaseInsensitiveUnionMaxMembers = 3;
/// A member name as a case-insensitive XSD regex (Tls12 → [tT][lL][sS]12).
private static string AnyCase(string name)
=> string.Concat(name.Select(c => char.IsLetter(c)
? $"[{char.ToLowerInvariant(c)}{char.ToUpperInvariant(c)}]"
: c.ToString()));
private static string OtherSideType(EndpointRole role)
=> role == EndpointRole.Producer ? "producerOnlyOption" : "consumerOnlyOption";
///
/// The types of an option written on the side that does not read it: an empty character class
/// admits no value, so any use is a validation error, and the type name is the explanation.
///
private static IEnumerable OtherSideTypes()
=> new[] { EndpointRole.Producer, EndpointRole.Consumer }.Select(role =>
new XElement(Xs + "simpleType", new XAttribute("name", OtherSideType(role)),
new XElement(Xs + "annotation",
new XElement(Xs + "documentation",
role == EndpointRole.Producer
? "Read only by the producer (): the consumer () refuses it."
: "Read only by the consumer (): the producer () refuses it.")),
new XElement(Xs + "restriction", new XAttribute("base", "xs:string"),
new XElement(Xs + "pattern", new XAttribute("value", "[a-[a]]")))));
// An option group member (SearchTerm.Subject) is written with every segment camelCase: searchTerm.subject.
private static string CamelCase(string name)
=> string.Join('.', name.Split('.').Select(part =>
part.Length > 0 && char.IsUpper(part[0]) ? char.ToLowerInvariant(part[0]) + part[1..] : part));
private static XElement Attribute(AttributeSpec spec)
{
var attribute = new XElement(Xs + "attribute", new XAttribute("name", spec.Name));
if (spec.Required)
attribute.Add(new XAttribute("use", "required"));
if (spec.Type is AttributeType.Enum && spec.EnumValues is { Count: > 0 } values)
{
attribute.Add(new XElement(Xs + "simpleType",
new XElement(Xs + "restriction", new XAttribute("base", "xs:string"),
values.Select(v => new XElement(Xs + "enumeration", new XAttribute("value", v))))));
}
else
{
attribute.Add(new XAttribute("type", BuiltInType(spec.Type)));
}
return attribute;
}
private static string BuiltInType(AttributeType type) => type switch
{
AttributeType.Bool => "xs:boolean",
AttributeType.Int => "xs:int",
AttributeType.Long => "xs:long",
AttributeType.Double => "xs:double",
// Duration is hh:mm:ss(.fff), not the ISO xs:duration — a string to the schema.
_ => "xs:string",
};
private static XElement ForeignAttributes()
=> new(Xs + "anyAttribute",
new XAttribute("namespace", "##other"),
new XAttribute("processContents", "lax"));
}