Data Types

Mapping

Below you can find the mapping of data types between python and xml schema.

Python

XML Type

str

anyAtomicType

anyURI

base

base64Binary

date

dateTime

dateTimeStamp

dayTimeDuration

yearMonthDuration

derivationControl

duration

ENTITIES

ENTITY

gDay

gMonth

gMonthDay

gYear

gYearMonth

hexBinary

ID

IDREF

IDREFS

lang

language

Name

NCName

NMTOKEN

NMTOKENS

normalizedString

NOTATION

simpleDerivationSet

string

time

token

object

anySimpleType

anyType

bool

boolean

int

byte

int

integer

long

negativeInteger

nonNegativeInteger

nonPositiveInteger

positiveInteger

short

unsignedByte

unsignedInt

unsignedLong

unsignedShort

decimal.Decimal

decimal

double

float

float

xml.etree.ElementTree

QName

enum.Enum

enumeration

Converters

The build-in converters are used to bind data from and to xml documents. They are also used partially for json data binding when the typing information is lost in the literal representation like enumerations.

The converter will attempt to convert values according to the provided list of possible types but in case of an error it will fall back to str, even if that means violating the field typing definition.

A warning will also be raised in that case.

ConverterWarning: Failed to convert value `a` to one of [<class 'float'>]

You can register your custom type converters if you are working with user defined models with types not supported from the default ones.

@dataclass
class Root:
    updated_at: datetime = field(metadata={"type": "Attribute"})


class DatetimeConverter(Converter):
    def from_string(self, value: str, **kwargs: Any) -> datetime:
        return datetime.fromisoformat(value)

    def to_string(self, value: datetime, **kwargs: Any) -> str:
        return value.isoformat(sep=" ")


converter.register_converter(datetime, DatetimeConverter())
root = XmlParser().from_string('<root updated_at="2011-11-04T00:05:23">', Root)

assert root == Root(updated_at=datetime(2011, 11, 4, 0, 5, 23))