Registry / serialization / xmlschema

xmlschema

JSON →
library4.3.2pypypi✓ verified 25d ago

xmlschema is a Python library for validating XML documents against XML Schema Definition (XSD) files and for decoding XML data into Python dictionaries. It supports XPath 1.0/2.0+ for schema processing and data extraction. The library is actively maintained with regular major and minor releases, typically several per year.

pip install xmlschema
INSTALL
IMPORT
SIG · XMLSCHEMA
X
xmlschema
serializationpythonv4.3.2
Install
2.0s avg
Import
587ms
Disk
22MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v4.3.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.617s · 23.6MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 2.0s · import 0.557s · 24MB
22MB installed
● package 22MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

XMLSchema
from xmlschema import XMLSchema
XMLResource
from xmlschema import XMLResource
ValidationError
from xmlschema import ValidationError

This quickstart demonstrates how to load an XML Schema, validate an XML document against it, and decode the validated XML into a Python dictionary. It also shows an example of how invalid XML is handled during validation.

import xmlschema # Define a simple XML Schema (XSD) and an XML document xsd_content = ''' <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="data"> <xs:complexType> <xs:sequence> <xs:element name="item" type="xs:string" maxOccurs="unbounded"/> </xs:sequence> </xs:complexType> </xs:element> </xs:schema> ''' xml_content = ''' <data> <item>First</item> <item>Second</item> </data> ''' # 1. Load the XML Schema try: schema = xmlschema.XMLSchema(xsd_content) print("Schema loaded successfully.") except xmlschema.XMLSchemaException as e: print(f"Schema error: {e}") exit(1) # 2. Validate an XML document against the schema try: schema.validate(xml_content) print("XML document is valid.") except xmlschema.ValidationError as e: print(f"XML validation error: {e}") # 3. Decode the XML document into a Python dictionary try: data_dict = schema.to_dict(xml_content) print("\nDecoded XML to dictionary:") print(data_dict) except xmlschema.ValidationError as e: print(f"Decoding error: {e}") # Example of invalid XML invalid_xml_content = ''' <data> <extra_item>This should not be here</extra_item> <item>Valid Item</item> </data> ''' try: schema.validate(invalid_xml_content) print("Invalid XML document is valid (ERROR!).") except xmlschema.ValidationError as e: print(f"Invalid XML correctly failed validation: {e.reason.splitlines()[0]}...")
Debug
Known issues
breakingPython 3.8 support was dropped in `xmlschema` v4.0.0, and Python 3.9 support was dropped in `xmlschema` v4.3.0. Users on older Python versions must use `xmlschema` v3.x or upgrade their Python interpreter.
fix
Upgrade your Python environment to 3.10 or newer. If stuck on Python 3.9, use `xmlschema<4.3.0`. If stuck on Python 3.8, use `xmlschema<4.0.0`.
affects: >=4.0.0, >=4.3.0
breakingVersion 4.0.0 introduced significant internal API changes, replacing generators with normal functions for decoding/encoding and standardizing on `DecodeContext` and `EncodeContext` instead of keyword arguments. Code directly interacting with these lower-level APIs or internal methods will break.
fix
Consult the `xmlschema` v4.x documentation for updated usage patterns, especially for custom decoding/encoding or schema loading processes. High-level methods like `validate()` and `to_dict()` are largely compatible.
affects: >=4.0.0
gotchaVersion 4.2.0 introduced package limits for schema sources (`MAX_SCHEMA_SOURCES`) and XML elements (`MAX_XML_ELEMENTS`), and reduced `MAX_XML_DEPTH`. These limits are designed to prevent resource exhaustion but can lead to `XMLSchemaResourceError` exceptions for very large or deeply nested schemas/documents if not configured.
fix
If encountering `XMLSchemaResourceError`, consider increasing the limits via `xmlschema.set_settings()` for `MAX_SCHEMA_SOURCES`, `MAX_XML_ELEMENTS`, or `MAX_XML_DEPTH` if your application legitimately requires larger resources. For example: `xmlschema.set_settings(max_xml_elements=5_000_000)`.
affects: >=4.2.0
gotchaWhile `xmlschema` can use `lxml` for improved parsing performance, it is an optional dependency. If `lxml` is not installed, the library falls back to Python's built-in `xml.etree.ElementTree`. Users expecting `lxml`'s speed or specific features (like `iterparse`'s `lxml` argument) must explicitly install it.
fix
Install `xmlschema` with the `lxml` extra: `pip install "xmlschema[lxml]"`. Then, some methods like `XMLResource.iterparse` can accept an `lxml=True` argument for `lxml`-specific behavior.
affects: All versions
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'xmlschema'
The `xmlschema` library is not installed in the Python environment where the code is being executed.
fix
Run `pip install xmlschema` in your terminal to install the library.
xmlschema.validators.exceptions.XMLSchemaValidationError: failed to decode value
The XML document being processed does not conform to the rules defined in the associated XML Schema Definition (XSD), leading to a validation failure during decoding.
fix
Review the XML document and adjust its content or structure to match the constraints (e.g., data types, required elements, enumerations) specified in the XSD. Use `schema.validate(xml_file)` for detailed error messages.
FileNotFoundError: No such file or directory: 'path/to/your/schema.xsd'
The XSD file path or URL provided to `xmlschema.XMLSchema()` is incorrect, the file does not exist at the specified location, or the program lacks the necessary permissions to access it.
fix
Verify that the path or URL to your XSD file is correct and that the file exists in the specified location. Ensure your application has read access to the file and its directory.
xmlschema.exceptions.XMLSchemaParseError: invalid XML schema
The XML Schema Definition (XSD) file itself is syntactically malformed, not well-formed XML, or contains structural errors that prevent `xmlschema` from parsing it correctly (e.g., missing required attributes like 'targetNamespace').
fix
Inspect the XSD file for XML well-formedness and schema validity. Correct any syntax errors, missing required attributes in schema definitions, or structural inconsistencies within the XSD itself.
Upgrade
Version history
4.3.2latest on PyPI · released Jun 30, 2026
Audit
Dependencies
elementpathrequiredCore dependency for XPath 1.0/2.0+ support required for schema processing.
lxmloptionalOptional dependency for faster XML parsing, especially when using the `iterparse` feature.
Agent activity
46 hits · last 30 days
node
38
Amazon
1
OpenAI (training)
1
Resources
xmlschema — pip install xmlschema · libregistry