dapper91 / pydantic-xml

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

Extra fields trigger "missing" validation error #67

Closed GuillaumeDesforges closed 1 year ago

GuillaumeDesforges commented 1 year ago

With a simple model:

from pydantic_xml import BaseXmlModel, attr, element

class Customer(BaseXmlModel, tag="Customer"):
    id: str | None = element()
    name: str = element()

this test fails

def test_deserialize_customer():
    customer_xml = (
        "<Customer><active>1</active><id>101</id><name>some_customer</name></Customer>"
    )

    customer = Customer.from_xml(customer_xml)
    assert customer is not None
    assert customer.id is not None

with error

>   ???
E   pydantic.error_wrappers.ValidationError: 1 validation error for Customer
E   name
E     field required (type=value_error.missing)

pydantic/main.py:341: ValidationError

versions:

$ pip list | grep pydantic
pydantic              1.10.9
pydantic-xml          0.6.3
dapper91 commented 1 year ago

@GuillaumeDesforges Hi.

If your document may contain extra fields you should use ordered search mode:

class Customer(BaseXmlModel, tag="Customer", search_mode='ordered'):
    id: str | None = element()
    name: str = element()

More details here

GuillaumeDesforges commented 1 year ago

Thanks for the quick and effective reply, this fixerd the issue!

from pydantic_xml import BaseXmlModel, attr, element
from pydantic_xml.element.element import SearchMode

class Customer(
    BaseXmlModel,
    tag="Customer",
    search_mode=SearchMode.ORDERED,
):
    id: str | None = element()
    name: str = element()
GuillaumeDesforges commented 1 year ago

In fact, SearchMode.UNORDERED is even better in my case