Expand description
XML Schema (XSD 1.0 and 1.1) validator with a post-schema-validation infoset (PSVI) and a built-in XPath 2.0 engine.
The crate parses and composes schema documents into a SchemaSet,
validates instances through a push-based API that event-based parsers
(quick-xml, through validation::drive_quick_xml) and DOM-style sources
(any DomNavigator, through validation::drive_navigator) can drive,
and reports the PSVI of every element and attribute. With the xsd11
feature it adds XSD 1.1 (assertions, type alternatives, open content), the
XPath 2.0 engine (xpath), a compact schema-aware document store
(document) and its typed build; compose adds XQuery-style composition
of XML from Rust.
The guides in doc/ of the repository walk through the API: the
Introduction for the entry points, the Architecture Overview, the
Extensibility guide, Generated Validation (validation tables written by a
build script, for schemas known when a project is built), Implementation
Limits, and — coming from 0.3.x — What’s New in 0.4 and Upgrading to 0.4
(from 0.2.x: What’s New in 0.3 and Upgrading to 0.3).
§Entry Points
| Task | Start here |
|---|---|
| Load one schema | load_and_process_schema |
Load related schemas, with loaders, a catalog or a LocationRewriter | SchemaSetBuilder |
| Choose XSD 1.0 or 1.1 semantics | SchemaSet::new / SchemaSet::xsd11 (the xsd11 feature only compiles the 1.1 code) |
| Find the directives whose documents could not be read | SchemaSet::directive_failures |
| Validate an instance | validation::SchemaValidator, validation::ValidationRuntime, a driver such as validation::drive_quick_xml |
| Validate against a stipulated declaration or type, or laxly | validation::ValidationRoot |
| Bound what an instance may contain | xml::ParseLimits |
Validate and build a typed document in one pass (xsd11) | document::build_typed_document_with, document::TypedBuildOptions |
Evaluate XPath 2.0 (xsd11) | xpath::XPathExpr, xpath::XPathContext |
§Cargo Features
Every feature is additive. This documentation is built with all of them, so it shows items a default build does not have:
| Feature | Default | Adds |
|---|---|---|
xsd11 | no | XSD 1.1 (assertions, type alternatives, open content), the XPath 2.0 engine (xpath), the document store and its typed build (document), drive_buffer_document |
compose | no | XQuery-style composition of XML from Rust (compose, the form! and xpath! macros); implies xsd11 |
async | no | asynchronous schema loading: AsyncSchemaLoader, SchemaSetBuilder::with_async_loader, add_async and compile_async, load_and_process_schema_async, load_schema_async |
unicode-normalization | yes | the normalization forms of fn:normalize-unicode (without it, a call that asks for one, the one-argument form included, raises an error) |
plan | no | validation modules written by a build script, in the crate that includes them: include_validator! and the plan module (check, validate, what they answer); for the dependency of a crate whose build dependency has codegen |
plan-build | no | the generator’s plan builder and emitter without the generator, with or without xsd11: support for this crate’s tests, not a public API in this release; implies plan |
codegen | no | the generator of validation modules, for a build script (codegen::Configuration); implies plan-build and xsd11 |
§Single Schema
Use load_and_process_schema for complete processing of a single schema.
XSD version is set on SchemaSet — the parser derives it automatically.
use xsd_schema::{SchemaSet, load_and_process_schema};
// Use SchemaSet::new() for XSD 1.0, SchemaSet::xsd11() for XSD 1.1
let mut schema_set = SchemaSet::new();
let xml = r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root" type="xs:string"/>
</xs:schema>"#;
let stats = load_and_process_schema(xml.as_bytes(), "schema.xsd", &mut schema_set, None)
.expect("failed to load schema");
assert_eq!(stats.doc_id, 0);§Multiple Related Schemas
SchemaSetBuilder loads documents and the documents their directives
name, then compiles them together. For documents you load yourself, use the
two-phase approach:
use xsd_schema::{SchemaSet, parse_schema_only, process_loaded_schemas};
let mut schema_set = SchemaSet::new();
let schemas = [
(r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:schema1">
<xs:element name="item1" type="xs:string"/>
</xs:schema>"#, "schema1.xsd"),
(r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="urn:schema2">
<xs:element name="item2" type="xs:int"/>
</xs:schema>"#, "schema2.xsd"),
];
// Phase 1: Parse all schemas
for (xml, uri) in schemas {
parse_schema_only(xml.as_bytes(), uri, &mut schema_set).expect("parse failed");
}
// Phase 2: Process all schemas together
// (redefine/override application, inline assembly, reference resolution,
// and the same schema checks as every other entry point)
// Note: all participating schemas — including redefine/override targets —
// must be parsed before calling this function.
let (inline_stats, resolution_stats) = process_loaded_schemas(&mut schema_set)
.expect("processing failed");§Validating an Instance
use xsd_schema::validation::{
drive_quick_xml, CollectingValidationSink, SchemaValidator, SchemaValidity, ValidationFlags,
};
use xsd_schema::SchemaSetBuilder;
let schema_set = SchemaSetBuilder::new()
.add_source(
r#"<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="qty" type="xs:positiveInteger"/>
</xs:schema>"#,
"qty.xsd",
)?
.compile()?
.into_schema_set();
let validator = SchemaValidator::new(&schema_set, ValidationFlags::default());
let (mut errors, mut warnings) = (Vec::new(), Vec::new());
let mut runtime = validator.start_run(CollectingValidationSink {
errors: &mut errors,
warnings: &mut warnings,
});
let outcome = drive_quick_xml("<qty>0</qty>".as_bytes(), &mut runtime, &schema_set)?;
drop(runtime);
assert_eq!(outcome.root_validity, Some(SchemaValidity::Invalid));
assert_eq!(errors[0].instance_path().unwrap().to_string(), "/Q{}qty[1]");§Advanced: Low-Level Parser
For custom pipelines, the low-level parser is available at parser::parse_schema.
This only performs Phase 1 (parsing + assembly) - subsequent phases must be run manually.
§Architecture
The parser uses a state machine approach with typed parser frames for each XSD element type. All schema components are stored in arenas with typed IDs to avoid reference cycles.
§Core Modules
xml- Reading XML text: well-formedness checks and parse limits for every readerparser- XSD document parsing with location tracking, directive resolutionnamespace- String interning and namespace managementschema- Schema component model (elements, types, groups)types- Type definitions, facets and typed valuescompiler- Content-model compilation and Unique Particle Attributionvalidation- Instance validation and the PSVIxpath,document(xsd11) - the XPath 2.0 engine and the document storecompose(compose) - XQuery-style composition of XML
Re-exports§
pub use error::FacetError;pub use error::FacetResult;pub use error::SchemaError;pub use error::SchemaLimit;pub use error::SchemaResult;pub use schema::SchemaDocument;pub use schema::SchemaSet;pub use schema::assemble_inline_types;pub use schema::resolve_all_references;pub use schema::InlineAssemblyStats;pub use schema::ResolutionStats;pub use schema::model::XsdVersion;pub use schema::model::RegexCompat;pub use types::BuiltinTypes;pub use types::PrimitiveTypeCode;pub use types::ValueKind;pub use types::XmlTypeCode;pub use types::facet_applicable;pub use types::facet_applicable_for_type;pub use types::normalize_whitespace;pub use types::FacetApplicability;pub use types::FacetFixed;pub use types::FacetKind;pub use types::FacetSet;pub use types::WhitespaceMode;pub use types::facets::clear_pattern_cache;pub use navigator::DomNodeType;pub use navigator::NamespaceAxisScope;pub use navigator::XmlNodeOrder;pub use xpath::BufferedNodeIterator;pub use xpath::EmptyIterator;pub use xpath::EvalValue;pub use xpath::ExternalVar;pub use xpath::FunctionCallRef;pub use xpath::RangeIterator;pub use xpath::TreeComparer;pub use xpath::TypedEvaluator;pub use xpath::VecNodeIterator;pub use xpath::XPathContext;pub use xpath::XPathEvaluator;pub use xpath::XPathExpr;pub use xpath::XmlItem;pub use xpath::XmlItemRef;pub use xpath::XmlNodeIterator;pub use pipeline::load_and_process_schema;pub use pipeline::load_schema;pub use pipeline::parse_schema_only;pub use pipeline::process_loaded_schemas;pub use pipeline::DirectiveStats;pub use pipeline::PipelineConfig;pub use pipeline::PipelineStats;pub use pipeline::load_and_process_schema_async;pub use pipeline::load_schema_async;pub use builder::CompilationStats;pub use builder::CompiledSchemaSet;pub use builder::SchemaSetBuilder;pub use parser::resolver::decode_xml_bytes;pub use parser::resolver::decode_xml_to_utf8_bytes;pub use parser::resolver::DirectiveFailure;pub use parser::resolver::EmbeddedLoader;pub use parser::resolver::FileSystemLoader;pub use parser::resolver::LoaderChain;pub use parser::resolver::LocationRequest;pub use parser::resolver::LocationRewriter;pub use parser::resolver::ResolverConfig;pub use parser::resolver::SchemaCatalog;pub use parser::resolver::SchemaLoader;pub use parser::resolver::SchemaResolver;pub use parser::resolver::AsyncSchemaLoader;pub use embedded::get_embedded_schema;pub use embedded::has_embedded_schema;pub use embedded::XLINK_NAMESPACE;pub use embedded::XLINK_XSD;pub use embedded::XML_NAMESPACE;pub use embedded::XML_XSD;pub use compiler::compile_model_group;pub use compiler::compile_particle;pub use compiler::find_complex_type;pub use compiler::fragment_to_table;pub use compiler::inspect_content_model;pub use compiler::CompileContext;pub use compiler::ContentModelReport;pub use compiler::FragmentBuilder;pub use compiler::NfaCompileError;pub use compiler::NfaCompileResult;pub use compiler::NfaFragment;pub use compiler::NfaState;pub use compiler::NfaTable;pub use compiler::NfaTerm;pub use compiler::NfaTransition;pub use compiler::StateId;pub use compiler::TransitionKind;pub use validation::error as validation_error;pub use validation::error_with_path as validation_error_with_path;pub use validation::facet_constraint_code;pub use validation::from_facet_error;pub use validation::from_value_error;pub use validation::value_error_constraint_code;pub use validation::ValidationError as InstanceValidationError;pub use validation::ValidationResult as InstanceValidationResult;pub use validation::hint_loader::enrich_schema_set;pub use validation::hint_loader::load_hints_into_builder;pub use validation::hint_loader::EnrichmentOutcome;pub use validation::hint_loader::HintLoadResult;pub use validation::info::NoNamespaceSchemaLocationHint;pub use validation::info::SchemaLocationHint;pub use ids::*;
Modules§
- arenas
- Arena storage for schema components
- builder
- SchemaSet builder with compile() pattern
- codegen
- The generator of validation modules, for a build script (feature
codegen). - compiler
- NFA compilation for XSD content models
- compose
- XQuery-style composition from Rust.
- document
- Page-based XML document buffer for XPath 2.0 evaluation.
- embedded
- Embedded schema assets
- error
- Error types for XSD parsing and validation
- ids
- Typed IDs for arena-based storage
- namespace
- Namespace management and string interning
- navigator
- DOM navigation trait and types
- parser
- XSD document parsing
- pipeline
- Schema processing pipeline
- plan
- Validation modules generated at build time: what they answer, and the
interpreter they run on (feature
plan). - regex_
convert - XML Schema / XPath 2.0 regex pattern conversion.
- schema
- Schema component model
- types
- XSD type definitions and facets
- validation
- Instance validation against XSD schemas
- xml
- Reading XML text: the well-formedness checks and parse limits shared by every reader of this crate.
- xpath
- XPath2 evaluation engine
Macros§
- form
- Describes a result element: a
Form, built eagerly and emitted later byComposer::build. - include_
validator - Declares the validation module a build script generated for a schema:
include_validator!(pub invoice)ispub mod invoice, its contents read from$OUT_DIR/invoice.rs, whichcodegen::Configurationwith.module("invoice")wrote (featurecodegenof the build dependency). Attributes and doc comments before the visibility go to the module. - xpath
- Evaluates an XPath expression on a
Composer.