Attributes#

Primitive types#

A field of a primitive type marked as pydantic_xml.attr() is bound to a local element attribute. Parameter name is used to declare the attribute name from which the data is extracted. If it is omitted the field name is used (respecting pydantic field aliases).

Model
class Company(BaseXmlModel):
    trade_name: str = attr(name='trade-name')
    type: str = attr()
Document
<Company trade-name="SpaceX" type="Private"/>
{
    "trade_name": "SpaceX",
    "type": "Private"
}

Namespaces#

The namespace can be defined for attributes as well. To bind a model field to a namespaced attribute pass parameter ns to a pydantic_xml.attr() and define a namespace map for the model.

Model
class Company(
    BaseXmlModel,
    nsmap={'co': 'http://company.org/co'},
):
    trade_name: str = attr(name='trade-name', ns='co')
    type: str = attr(ns='co')
Document
<Company co:trade-name="SpaceX"
         co:type="Private"
         xmlns:co="http://company.org/co"/>
{
    "trade_name": "SpaceX",
    "type": "Private"
}

Namespace inheritance#

The attribute namespace can be inherited from the model. To make attributes inherit the model namespace define the model-level namespace and namespace map and set ns_attrs flag.

Model
class Company(
    BaseXmlModel,
    ns_attrs=True,
    ns='co',
    nsmap={'co': 'http://company.org/co'},
):
    trade_name: str = attr(name='trade-name')
    type: str = attr()
Document
<co:Company co:trade-name="SpaceX"
            co:type="Private"
            xmlns:co="http://company.org/co"/>
{
    "trade_name": "SpaceX",
    "type": "Private"
}