dapper91 / pydantic-xml

python xml for humans
https://pydantic-xml.readthedocs.io
The Unlicense
141 stars 14 forks source link

boolean serialised with uppercase first letter #126

Closed maurosilber closed 8 months ago

maurosilber commented 9 months ago

I'm not sure if this is an invalid XML, but in https://www.w3.org/TR/xmlschema-2/#boolean says that the valid values are {true, false, 1, 0}:

from pydantic_xml import BaseXmlModel, attr

class Model(BaseXmlModel):
    x: bool = attr()

print(
    Model
    .from_xml(b'<Model x="true" />')
    .to_xml()
    .decode()
)
<Model x="True"/>
dapper91 commented 8 months ago

The library encodes values as is by default. But you can easily define your own encoding format for any type:

from typing import Annotated
from pydantic import PlainSerializer
from pydantic_xml import BaseXmlModel, attr

XmlBool = Annotated[bool, PlainSerializer(lambda val: str(val).lower())]

class Model(BaseXmlModel):
    x: XmlBool = attr()

print(Model.from_xml(b'<Model x="true" />').to_xml().decode())
maurosilber commented 8 months ago

Yes, I did that, thanks.

But shoudn't it by default encode the Python True as the string "true", which is what the XML specification says?

dapper91 commented 8 months ago

@maurosilber Yes, that sounds reasonable, fixed it in version 2.3.0.