xmlschema 0.0.17

XML Schema (XSD) validation for Rust, with zero unsafe code
Documentation

Contents

Getting started

The xmlschema ecosystem

Library reference

Operational


Install

As a Rust library

[dependencies]
xmlschema = "=0.0.17"
oxml = "=0.0.17"

Use the oxml version xmlschema itself pins, so a document crossing the core/schema boundary is one Rust type. 0.0.1 on crates.io is the old crate, which exposed no public API at all; do not use it.


Requirements

  • Rust 1.89.0 or later (rust-version in Cargo.toml, built in CI with exactly that compiler). Policy: doc/POLICIES.md.
  • One runtime dependency, oxml, with default features off and only std and xpath enabled.
  • Platforms: CI tests on Linux, macOS and Windows, and checks the library builds for wasm32-unknown-unknown. There is no C code and no FFI.
  • No network or filesystem access is needed or performed.

Quick Start

use xmlschema::{parse_schema, validate};

let xsd = r#"
  <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="book">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="title" type="xs:string"/>
        </xs:sequence>
        <xs:attribute name="lang" type="xs:string" use="required"/>
      </xs:complexType>
    </xs:element>
  </xs:schema>
"#;

let schema = parse_schema(xsd)?;
let doc = oxml::parse("<book lang='en'><title>Dune</title></book>")?;

assert!(validate(&doc, &schema).is_valid());
# Ok::<(), Box<dyn std::error::Error>>(())

Parse a schema once and validate as many documents against it as you like. Every violation is reported, each with a path:

/invoice/issued — `22/08/2026` is not a valid date (YYYY-MM-DD)
/invoice/line[1]/@currency — `pounds` does not match the pattern `[A-Z]{3}`
/invoice/line[1]/amount — -5 must be greater than 0
/invoice/line[2] — missing required attribute `currency`
/invoice/line[2]/amount — `not a number` is not a valid decimal

The xmlschema ecosystem

Every member of the oxml family ships the same version number, so there is never a compatibility table to consult.

Component Purpose Use case
oxml Core: parser, tree, XPath 1.0 Parse and query XML in safe Rust
oxml-cli Command-line querying, formatting and validation XML work from a shell or script
oxml-lsp XML analysis and linting; the LSP transport is not yet implemented Diagnostics for editors and CI
oxml-mcp Model Context Protocol server XML tools for AI agents
oxml-wasm WebAssembly bindings XML in the browser and Node
oxml-json A small JSON value, parser and serialiser The family's JSON-RPC transport
xmlschema XSD validation Validate documents against an .xsd, within the limits below

This crate keeps its published name rather than being folded into oxml. The name means XSD validation specifically, and repurposing it would hand existing users something different under a name they already depend on.


Capabilities at a glance

Area Capability Status
Schema parsing Elements, model groups, cardinality, attributes ✅
Simple types All 44 built-ins, 12 restriction facets ✅
xs:list and xs:union Lists and unions of simple types ✅
xs:all, xs:group, xs:attributeGroup Named and unordered groups ✅
xs:any and xs:anyAttribute Namespace constraints and processContents ✅
Complex-type derivation Extension, restriction, and Particle Valid (Restriction) ✅
Schema validity XSD's own structural rules ✅
xs:pattern Own engine, XSD dialect including class subtraction ✅
Diagnostics Every violation, each with a path ✅
Identity constraints key, keyref, unique with scoped selectors and fields ✅
xs:import / xs:include Through a caller-supplied SchemaSource ✅
Conformance 96.1% of the decided tests in the 39,420-test W3C XSD suite, ratcheted ✅
Tests 248 tests, plus the conformance suite ✅
Substitution groups, xs:redefine ✗

An unsupported construct is skipped rather than rejected: the surrounding rules still apply, so a schema using one validates everything else correctly instead of failing wholesale.

What was skipped is reported. support::unsupported audits a schema against what this crate enforces and names everything it does not, so "this document is valid" and "this document was checked" are never confused. Details: doc/COVERAGE.md.


Ecosystem comparison

Rust has had no pure-Rust XSD validator; the only option was libxml, which binds libxml2 through C-FFI.

Project XSD validation Pure Rust WASM
xmlschema ✅ 96.1% of the W3C suite's decided tests ✅ ✅
libxml ✅ ✗ (C-FFI) ✗
quick-xml, roxmltree, xot ✗ ✅ ✅

libxml remains the more complete implementation. The difference is what it costs: a C toolchain, unsafe, no WebAssembly target, and libxml2's CVE stream.

See doc/COMPARISON.md for the evidence and complete matrix.


Benchmarks

Three Criterion benchmarks, split because they answer different questions: parsing a schema (the expensive half, done once), validating documents (the cheap half, repeated), and the xs:pattern engine.

Scenario Result Environment
cargo bench --bench schema not published see below
cargo bench --bench validate not published see below
cargo bench --bench pattern not published see below

No absolute figures are published: on the maintainer's machine one case returned confidence intervals spanning 566–906 µs, a spread wider than most changes worth measuring. A figure without its conditions is not a measurement.

See doc/BENCHMARKS.md for methodology and full results.


Features

  • parse_schema / parse_schema_with read an .xsd into an immutable Schema, enforcing XSD's structural rules on the schema itself. parse_schema_with resolves xs:import and xs:include through a SchemaSource you supply; parse_schema uses NoSchemas.

  • validate returns a Report, not a Result. A document can be wrong in several independent ways, and stopping at the first means fixing them one build at a time. Each Violation carries a path and a message; the path is positional (line[1] is the first line child), so it identifies one element:

    /order: missing required attribute `id`
    /order: expected `customer` exactly once, found 0
    /order/line[1]/qty: `many` is not a valid integer
    
  • datatype models every XSD 1.0 built-in separately, so xs:byte rejects 999 rather than validating as an unbounded integer.

  • pattern is a hand-written engine for XSD's regular-expression dialect (always anchored, no captures, its own escapes), with bounded nesting, quantifiers and backtracking. Why: doc/PATTERNS.md.

  • derive decides Particle Valid (Restriction): whether one content model is a valid restriction of another.

  • support::unsupported names what a given schema uses that this crate does not enforce.

Architecture: doc/ARCHITECTURE.md.


Configuration

There are no Cargo features and no global settings. The one choice is how schemas referenced by xs:import and xs:include are found:

Entry point Imports and includes
parse_schema(xsd) Not resolved; reported by support::unsupported as unenforceable
parse_schema_with(xsd, &source) Resolved by your SchemaSource, by schemaLocation

Parser limits for the XML itself (depth, entity expansion budgets) are oxml's; see its documentation.


Examples

examples/ is compiled and run in CI, and CI requires the examples together to execute every public function.

Example What it shows
validate Parsing a schema once, validating many, and reading a Report
datatypes What a built-in datatype knows about its own values
patterns Compiling and applying an xs:pattern facet
restriction Deciding whether one content model restricts another
cargo run --example validate

When not to use xmlschema

  • You need complete XSD 1.0. Check Capabilities at a glance and support::unsupported against your schemas first. A document can be reported valid when a skipped construct would have rejected it.
  • You need XSD 1.1 (assertions, conditional type assignment). Xerces has it.
  • You need automatic schema fetching. Imports and includes require parse_schema_with and a caller-supplied SchemaSource; no network or filesystem resolver exists.
  • You need to validate while streaming. The document is parsed in full first.

Development

./scripts/gate.sh                                     # everything CI runs, fastest failure first
cargo run --release -p xmlschema-conformance --bin download
cargo test --release -p xmlschema-conformance         # the W3C XSD suite
python3 scripts/check-complexity.py                   # the complexity ratchet
python3 scripts/check-readme.py                       # this README against the template

The gate runs format, clippy, tests, rustdoc, the #![forbid(unsafe_code)] check, the examples, the W3C XSD conformance suite, the 95% coverage floor, the complexity ratchet and an MSRV build. It pins the toolchain rather than trusting rust-toolchain.toml, because a RUSTUP_TOOLCHAIN in the environment silently overrides that file.

The conformance step is skipped loudly when the suite has not been downloaded, and counts as a failure rather than vanishing. fuzz/ holds cargo-fuzz targets. CI runs the same set on Linux, macOS and Windows. How it is verified: doc/TESTING.md.


Security

XSD validation is normally applied to untrusted documents, so the parser's threat model is part of this crate's. It inherits oxml's posture:

  • No automatic external retrieval. Nothing here opens a file or a socket. Internal entity expansion is supported within oxml's budgets; caller-supplied schema resolution is the caller's trust boundary.
  • No unsafe. #![forbid(unsafe_code)], enforced at compile time.
  • Bounded pattern matching. Nesting depth, quantifier bounds and backtracking steps are capped.
  • Supply chain. One runtime dependency; cargo deny and cargo audit in CI; actions pinned by SHA.

Scorecard scans use a digest-pinned upstream image. Results are retained as CI artifacts and repository posture findings in GitHub code scanning, not published to Scorecard's public service. The badge shows workflow status, not a security score; a successful scan can still report findings.

Report vulnerabilities according to SECURITY.md.


Documentation


Stability guarantees

  • SemVer axis. Pre-1.0, each 0.0.x release may change the public API; a change that does is called out in the CHANGELOG. The family moves together by 0.0.1 per release, and siblings are pinned exactly (=).
  • Output stability. No promise beyond the SemVer axis: pre-1.0, a Violation's path format and message wording may change in any release, and a change is recorded in the CHANGELOG.
  • Minimum toolchain discipline. The MSRV is rust-version in Cargo.toml, built with exactly that compiler in CI. Raising it is a deliberate, recorded change (doc/POLICIES.md).
  • Conformance ratchet. The W3C suite's pass count is held by a committed baseline and may not fall.

License

Licensed under either of

at your option.

With thanks to libxml2, the reference implementation and the yardstick for behaviour; the W3C, for the XML Schema specification; and python-xmlschema, proof that a readable, standalone XSD implementation is achievable.