tefra / xsdata-pydantic

Naive XML & JSON Bindings for python pydantic classes!
https://xsdata-pydantic.readthedocs.io/
MIT License
52 stars 10 forks source link

Issue with optional fields with flag --ouput pydantic vs dataclass #28

Open lionpeloux opened 5 months ago

lionpeloux commented 5 months ago

Hi @tefra,

Your package looks promising. I encountered an issue while generating models from a xsd. The dataclass models work fine while the pydantic models don't.

It seems to me that there is a problem in how optional fields are generated (only for --output pydantic) You'll see the difference in the following image (for the same initial DPEv2.2.xsd file), where fields where tagged "optional" in the dataclass version while they were not in the pydantic. Maybe this is due to the fact that these fields are grouped in a <xsd:all> tag ?!

dataclass (left) vs  pydantic (right)

I generated the models from the same xsd like this :

xsdata DPEv2.2.xsd --package models_dataclass
xsdata DPEv2.2.xsd --output pydantic --package models_pydantic

And run the following code on a sample xml file

# Uncomment to work on models_pydantic version
# from models_pydantic import Dpe
# from xsdata_pydantic.bindings import XmlParser

# Uncomment to work on models_dataclass version
from models_dataclass import Dpe
from xsdata.formats.dataclass.parsers import XmlParser

parser = XmlParser()
result = parser.parse("2344E0308327N.xml", Dpe)

murs = result.logement.enveloppe.mur_collection.mur
for mur in murs:
    print(mur.donnee_entree.surface_paroi_totale)

You'll find the example xsd and xml files here : mwe.zip