PureXML/Sources/Schema/RelaxNGSchema.swift
Mihaela Mihaljevic b19e48a6eb feat(schema): RELAX NG pattern model, parser, and derivative validation
Add the RELAX NG pattern algebra (Pattern, NameClass), a parser for the XML
syntax into a grammar of start plus named defines, and James Clark's
derivative validation algorithm. The pattern is derived through each
start-tag, attribute, text, and end-tag event with simplifying constructors;
the document is valid when the residual pattern is nullable. Supports
element, attribute, text, empty, notAllowed, group, choice, interleave,
optional, zeroOrMore, oneOrMore, mixed, list, ref/define, data, value, and
the name classes; handles interleave and recursive grammars, reusing the XSD
datatype library for data and value.

Closes #11
Closes #12
2026-06-08 06:49:37 +02:00

24 lines
871 B
Swift

public extension PureXML.Schema {
/// A compiled RELAX NG schema (XML syntax). `validate(_:)` checks an instance
/// document by the derivative algorithm.
struct RelaxNG: Sendable {
private let start: Pattern
private let defines: [String: Pattern]
/// Compiles a RELAX NG schema document.
public init(_ rng: String) throws {
(start, defines) = try RelaxNGParser.parse(rng)
}
/// Whether `xml` is valid against the schema.
public func validate(_ xml: String) throws -> Bool {
guard case let .document(children) = try PureXML.parse(xml),
let root = children.compactMap(\.element).first
else {
return false
}
return RelaxNGEngine(defines: defines).matches(start: start, root: .element(root))
}
}
}