xsdata-pydantic

raw JSON →
24.5 verified Mon Apr 27 auth: no python

xsdata-pydantic is a plugin for xsdata that generates Pydantic models from XML Schema (XSD) documents. It provides a code generator producing Python classes with Pydantic v1 or v2 support, data binding, and serialization. The current version is 24.5, compatible with Python >=3.8 and xsdata >=22.10. Release cadence is irregular.

pip install xsdata-pydantic
error ModuleNotFoundError: No module named 'xsdata_pydantic'
cause The package is not installed or installed under a different name.
fix
Run 'pip install xsdata-pydantic'
error AttributeError: module 'xsdata_pydantic' has no attribute 'PydanticExtension'
cause Using an older version (<24.0) where the extension was named differently or not yet introduced.
fix
Upgrade xsdata-pydantic to version 24.0+: 'pip install --upgrade xsdata-pydantic'
error pydantic.errors.PydanticUserError: Field name "type" shadows a BaseModel attribute; use a different field name
cause XML schema has an element named 'type' which conflicts with Pydantic's built-in type field.
fix
Use xsdata's renaming feature: add '--field-name-policy' or customize the generator to rename conflicting fields.
breaking In version 24.x, Pydantic v2 is the default. If you need Pydantic v1, you must explicitly set the extension with PydanticV1Extension.
fix Use 'from xsdata_pydantic import PydanticV1Extension' and pass it as the extension.
gotcha The generated models are dataclasses with Pydantic validation. They cannot be directly used with raw Pydantic BaseModel methods like .model_dump_json(). Use the xsdata XmlSerializer instead.
fix Use XmlSerializer from xsdata to serialize to XML, or convert to dict/list manually.
deprecated Python 3.8 support will be dropped in a future release. Ensure you use Python 3.9+ for new projects.
fix Upgrade to Python 3.9 or later.

Install the plugin, generate Pydantic models using xsdata CLI with the extension, then parse and serialize XML data.

from xsdata_pydantic import PydanticExtension
from xsdata.formats.dataclass.serializers import XmlSerializer
from xsdata.formats.dataclass.parsers import XmlParser

# Generate models from XSD using CLI or code generator
# Example: xsdata my-schema.xsd --package mypackage --extension PydanticExtension

# After generation, use parser and serializer
parser = XmlParser()
serializer = XmlSerializer()