<p align="center">
<img src="https://oxmllib.com/assets/logo.svg" alt="xmlschema logo" width="128" />
</p>
<h1 align="center">xmlschema</h1>
<p align="center">
XML Schema (XSD) validation for Rust, with zero <code>unsafe</code> code: the schema member of the <a href="https://github.com/sebastienrousseau/oxml">oxml</a> family.
</p>
<p align="center">
<a href="https://github.com/sebastienrousseau/xmlschema/actions"><img src="https://img.shields.io/github/actions/workflow/status/sebastienrousseau/xmlschema/ci.yml?style=for-the-badge&logo=github" alt="Build" height="28" /></a>
<a href="https://crates.io/crates/xmlschema"><img src="https://img.shields.io/crates/v/xmlschema.svg?style=for-the-badge&color=fc8d62&logo=rust" alt="Registry" height="28" /></a>
<a href="https://docs.rs/xmlschema"><img src="https://img.shields.io/badge/docs.rs-xmlschema-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" alt="Docs" height="28" /></a>
<a href="https://github.com/sebastienrousseau/xmlschema/actions/workflows/scorecard.yml"><img src="https://img.shields.io/github/actions/workflow/status/sebastienrousseau/xmlschema/scorecard.yml?style=for-the-badge&label=Scorecard%20scan&logo=openssf" alt="Scorecard scan workflow status" height="28" /></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0%20OR%20MIT-blue.svg?style=for-the-badge" alt="License: Apache-2.0 OR MIT" height="28" /></a>
<a href="https://github.com/sebastienrousseau/xmlschema/blob/main/doc/POLICIES.md"><img src="https://img.shields.io/badge/MSRV-1.89.0-93450a.svg?style=for-the-badge&logo=rust" alt="MSRV 1.89.0" height="28" /></a>
<a href="https://www.bestpractices.dev/projects/14315"><img src="https://img.shields.io/cii/level/14315?style=for-the-badge&label=OpenSSF%20Best%20Practices&logo=openssf" alt="OpenSSF Best Practices" height="28" /></a>
</p>
<p align="center">
<img src="https://raw.githubusercontent.com/sebastienrousseau/xmlschema/main/.github/demo.gif" alt="cargo run --example validate: a schema parsed once, documents validated against it, and every violation reported with its path" width="100%" />
</p>
---
## Contents
**Getting started**
- [Install](#install): Cargo
- [Requirements](#requirements): toolchain floor, platforms
- [Quick Start](#quick-start): validate a document in ten lines
**The xmlschema ecosystem**
- [The xmlschema ecosystem](#the-xmlschema-ecosystem): oxml, oxml-cli, oxml-lsp, oxml-mcp, oxml-wasm, oxml-json and this crate
**Library reference**
- [Capabilities at a glance](#capabilities-at-a-glance): the current surface by theme
- [Ecosystem comparison](#ecosystem-comparison): short matrix; full table at [`doc/COMPARISON.md`](doc/COMPARISON.md)
- [Benchmarks](#benchmarks): what is measured; method at [`doc/BENCHMARKS.md`](doc/BENCHMARKS.md)
- [Features](#features): module-level capability list
- [Configuration](#configuration): core options
- [Examples](#examples): runnable example index
**Operational**
- [When not to use xmlschema](#when-not-to-use-xmlschema): limitations
- [Development](#development): the gate, fuzzing, CI
- [Security](#security): guarantees and compliance
- [Documentation](#documentation): all reference docs
- [Stability guarantees](#stability-guarantees): SemVer axis, output stability, minimum toolchain discipline
- [License](#license)
---
## Install
### As a Rust library
```toml
[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`](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
```rust
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:
```text
/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.
| [`oxml`](https://github.com/sebastienrousseau/oxml) | Core: parser, tree, XPath 1.0 | Parse and query XML in safe Rust |
| [`oxml-cli`](https://github.com/sebastienrousseau/oxml-cli) | Command-line querying, formatting and validation | XML work from a shell or script |
| [`oxml-lsp`](https://github.com/sebastienrousseau/oxml-lsp) | XML analysis and linting; the LSP transport is not yet implemented | Diagnostics for editors and CI |
| [`oxml-mcp`](https://github.com/sebastienrousseau/oxml-mcp) | Model Context Protocol server | XML tools for AI agents |
| [`oxml-wasm`](https://github.com/sebastienrousseau/oxml-wasm) | WebAssembly bindings | XML in the browser and Node |
| [`oxml-json`](https://github.com/sebastienrousseau/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
| 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`](doc/COVERAGE.md).
---
## Ecosystem comparison
Rust has had no pure-Rust XSD validator; the only option was `libxml`,
which binds libxml2 through C-FFI.
| **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`](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.
| `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`](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:
```text
/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`](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`](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:
| `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/`](examples/) is compiled and run in CI, and CI requires the
examples together to execute every public function.
| [`validate`](examples/validate.rs) | Parsing a schema once, validating many, and reading a `Report` |
| [`datatypes`](examples/datatypes.rs) | What a built-in datatype knows about its own values |
| [`patterns`](examples/patterns.rs) | Compiling and applying an `xs:pattern` facet |
| [`restriction`](examples/restriction.rs) | Deciding whether one content model restricts another |
```bash
cargo run --example validate
```
---
## When not to use xmlschema
- **You need complete XSD 1.0.** Check
[Capabilities at a glance](#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
```bash
./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`](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`](SECURITY.md).
---
## Documentation
- [API documentation](https://docs.rs/xmlschema)
- [`doc/`](doc/README.md): architecture, coverage, patterns, testing,
comparison, benchmarks, migration from `xmllint` and `libxml`, FAQ,
policies and roadmap
- [CHANGELOG.md](CHANGELOG.md) and [`doc/release-notes/`](doc/release-notes/)
- The XML library's documentation:
<https://github.com/sebastienrousseau/oxml/tree/main/doc>
---
## 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`](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
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE))
- MIT license ([LICENSE-MIT](LICENSE-MIT))
at your option.
With thanks to [libxml2](https://gitlab.gnome.org/GNOME/libxml2), the
reference implementation and the yardstick for behaviour; the
[W3C](https://www.w3.org/TR/xmlschema11-1/), for the XML Schema
specification; and
[python-xmlschema](https://github.com/sissaschool/xmlschema), proof
that a readable, standalone XSD implementation is achievable.