Pydantic XML Extension

2.19.0 · active · verified Sat Apr 11

Pydantic-xml is a Pydantic extension that provides XML binding for model fields, enabling seamless XML serialization and deserialization. It is deeply integrated with Pydantic, supporting most of its features. The library is actively maintained, with frequent releases addressing bug fixes and new features, often several times a month.

Warnings

Install

Imports

Quickstart

This example demonstrates how to define XML serializable/deserializable models using `BaseXmlModel`, bind fields to XML attributes (`attr`), elements (`element`), and handle lists of sub-models. It covers both deserialization from an XML string and serialization back to XML.

from typing import List, Optional
from pydantic import HttpUrl
from pydantic_xml import BaseXmlModel, attr, element

class Product(BaseXmlModel):
    status: str = attr() # e.g., 'running', 'development'
    launched: Optional[int] = attr(default=None)
    title: str # Extracted from the element text

class Company(BaseXmlModel, tag='Company'):
    trade_name: str = attr(name='trade-name')
    website: HttpUrl = element()
    products: List[Product] = element(tag='product', default_factory=list)

xml_doc = """
<Company trade-name="SpaceX">
    <website>https://www.spacex.com</website>
    <product status="running" launched="2013">Several launch vehicles</product>
    <product status="running" launched="2019">Starlink</product>
    <product status="development">Starship</product>
</Company>
"""

# Deserialize XML to a Pydantic model
company = Company.from_xml(xml_doc)
print(f"Company: {company.trade_name}, Website: {company.website}")
for product in company.products:
    print(f"  Product: {product.title}, Status: {product.status}, Launched: {product.launched}")

# Serialize Pydantic model back to XML
new_xml_doc = company.to_xml(pretty_print=True)
print("\nSerialized XML:")
print(new_xml_doc.decode())

view raw JSON →